Perl的数组操作有四大常用函数,分别是:
1、push:从数组的末尾加入元素
#!/usr/bin/perl
use strict;
use warnings;
my @array = ();
for ( my $i = 1 ; $i<= 5 ; ++$i ) {
push @array,$i;
print "@array\n";
}
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 1, 2, 3, 4, 5, 6);
while (@array) {
my $firstTotal = pop(@array);
print "@array\n";
}
3、shift: 从数组的开头取出元素
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 1, 2, 3, 4, 5, 6);
while (@array) {
my $firstTotal = shift(@array);
print "@array\n";
}
#!/usr/bin/perl
use strict;
use warnings;
my @array = ();
for ( my $i = 1; $i<= 5; ++$i ) {
unshift( @array, $i); # add $i to front of @array
print "@array\n"; # display current @array
}
5、splice操作数组中间部分的函数,该函数主要有2个作用:
5.1、向数组中间插入内容
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0 .. 6 );
my @array1 = ( 'a' .. 'd' );
my @replaced = splice( @array, 3,2, @array1 );
print "replaced: @replaced\n",
"with: @array1\n",
"resulting in: @array\n\n";
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0.. 6 );
my @array1 = ( 'a' .. 'd' );
my @replaced = splice( @array, 3,2 );
print "replaced: @replaced\n",
"resulting in: @array\n\n";
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0.. 6 );
my @array1 = ( 'a' .. 'd' );
my @replaced = splice( @array, 3);
print "replaced: @replaced\n",
"resulting in: @array\n\n";
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0 .. 6 );
my $replaced = join("\n", @array);
print "$replaced\n",
perl -le '$p=q(/var/ftp/test);@a=split(/\/ftp\//,$p);print $a[1];'
test
perl -le '$p=q(/var/ftp/test);@a=split(/\/ftp\//,$p);print $a[0];'
/var
8、scalar:统计数组的长度,一般我们不用这个,直接将数组赋值给标量即可。
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0 .. 6 );
my $count1 = @array;
my $count2 = scalar @array;
print "$count1\n";
print "$count2\n";
9、sort:对数组元素进行排序
#!/usr/bin/perl
use strict;
use warnings;
my @array = ( 0.. 9 );
my @reversed = reverse @array;
print "Original: @array\n";
print "Reversed: @reversed\n\n";
# create an unsorted array ofnumbers and sort it
my @array2 = ( 100, 23, 9, 75, 5, 10, 2, 50, 7, 96, 1, 40 );
my @sortedLexically = sort @array2;
my @sortedNumerically = sort { $a <=>$b } @array2;
print "Unsorted: @array2\n";
print "Lexically: @sortedLexically\n"; // 1 10 100 2 23 40 550 7 75 9 96
print "Numerically: @sortedNumerically\n"; // 1 2 5 7 9 10 23 40 50 75 96 100