[转 - 改] Perl初级教程 (二)

本文深入探讨了Perl编程中的字符串操作和数组应用,包括赋值语句、互操作性、数组访问与操作,以及如何利用数组进行多变量赋值。通过实例演示了如何使用Perl进行字符串拼接、字符追加、数组初始化、增删元素及多变量赋值,提供了丰富的编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于字符串】

$b = 'BB';
$c = 'CC';
$a = 'AA';

 

$a = $b . $c;   # Concatenate $b and $c = BBCC
$a = $b x $c;   # $b repeated $c times

 

Perl的赋值语句】

$a = $b;      # Assign $b to $a
$a += $b; # Add $b to $a  (算数运算)
$a -= $b; # Subtract $b from $a
$a .= $b; # Append $b onto $a (字符运算)


 互操作性】

 

$b = 'Pear';
$c = 'CC';
$a = 'Apple';


print $a.' and '.$b; 
print "\n";    # 制表符(\t) 换行(\n)
print '$a and $b';
print "\n";
print "$a and $b";

 

数组变量

数组通过以0开始的索引进行访问,方括号内为索引值

@List = ("1",2,'3');

print @List;

> 123

 

【 数组 赋值/删减 

 

@List = ("1",2,'3',"Array");

@array = (5..15);   #序列化列表5~15;

print @List;

print "\n";

print @array;

>123Array

  56789101112131415

 

# push Statement.

push(@List,"Added");

print @List;

print "\n";

push(@List,@array);

print @List;

>123Array

  123Array56789101112131415

 

# pop Statement.

 

@List = ("1",2,'3',"Array");
@array = (5..15);
push(@List,@array);
$e =  pop(@List);
$f =  pop(@List);


print $f;
print "\n";
print @List;
print "\n";
$f = @List;
print $f;

 

> 14

   123Array568910111213

   13

 

 # 数组也可以用来为多个标量进行赋值

 

@List = ("1",2,'3',"Array");
@array = (5..15);
push(@List,@array);
$e =  pop(@List);
$f =  pop(@List);
print "\n";
print $e;
print "\n";
print $f;
print "\n";

($e,$f,$a) = @List;      # 按照数组顺序项给变量赋值。

print "\n";
print $e;
print "\n";
print $f;
print "\n";
print $a;

 

 

> 15

   14

   1

   2

   3

 

# 最后,你可能想知道列表中最后一个元素的索引值,可以用这个表达式:

print $#List;

> 12;

 

 ($a, $b) = ($c, $d); # Same as $a=$c; $b=$d;
($a, $b) = @food; # $a and $b are the first two items of @food.
($a, @somefood) = @food; # $a is the first item of @food , @somefood is a list of the others.
(@somefood, $a) = @food; # @somefood is @food and $a is undefined.

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值