Reputation: 4926
I don't have too much practice in perl but I remember from my old days that you could get some elements of an array returned by a function in a single line, saving you time and code as not to save stuff first to a temporary array just to use a couple of their elements.
For instance
($a,$b,$c)=split(/:/, "stack:over:flow");
print "$b $c" # prints "over flow"
Or even
($a)=(split(/:/, "stack:over:flow"))[2];
print $a # prints "flow"
Let's say that I am only interested on the second and third elements ("over" and "flow") from the output of split
.
Can I do something like
($a,$b)=(split(/:/, "stack:over:flow"))[2,3];
Upvotes: 1
Views: 60
Reputation: 37146
Almost. Remember that arrays are zero-indexed.
my ( $first, $second ) = ( split /:/, "stack:over:flow" )[1,2];
Other points to note:
use strict; use warnings;
$a
and $b
as variable names. They are special package variables intended to be used inside sort
blocks.Upvotes: 3
Reputation: 483
well, yes, you can get it as there is an method to slice an array by index. here list a script you can run
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 my $text = "first:second:third";
6 my @array = split(':', $text);
7 my @new_array = @array[1, 2];
8 print "@new_array\n";
Upvotes: 0