use strict;
use warnings;
my @array = ('ray', 'loca', 'simon', 'ray');
my $wanted = 'ray';
print "***show howto delete elements from array***\n\n";
print "Old array is @array\n";
# Method One: using grep
@array = grep { $_ ne "$wanted" } @array;
print "Now array is @array\n";
# Method Two: using map
@array = ('ray', 'loca', 'simon', 'ray');
# Function: if the the input string isn't the wanted string
# return the input string.
sub my_print
{
my ( $input, $wanted ) = @_;
return $input if ( $input ne $wanted );
}
@array = map { my_print($_, "$wanted") } @array;
print "Now array is @array\n";
# Method Three: using splice or delete
@array = ('ray', 'loca', 'simon', 'ray');
# The position of first "ray" is 0
splice (@array, 0, 1);
print "Now array is @array\n";
# The position of first "ray" is 2
splice @array, 2, 1;
print "Now array is @array\n";
程序运行结果为:
[ray@localhost perl]$ ./array_ops.pl
***show howto delete
elements from array***
Old array is ray loca simon ray
Now array is
loca simon
Now array is loca simon
Now array is loca simon ray
Now
array is loca simon