1

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];
pedrosaurio
  • 4,708
  • 11
  • 39
  • 53

3 Answers3

3

Almost. Remember that arrays are zero-indexed.

my ( $first, $second ) = ( split /:/, "stack:over:flow" )[1,2];

Other points to note:

  • use strict; use warnings;
  • Avoid using $a and $b as variable names. They are special package variables intended to be used inside sort blocks.
Community
  • 1
  • 1
Zaid
  • 36,680
  • 16
  • 86
  • 155
2

You can also assign to undef anything you aren't interested in:

my (undef, $over, $flow) = split /:/, 'stack:over:flow';
RobEarl
  • 7,862
  • 6
  • 35
  • 50
0

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";
blio
  • 473
  • 5
  • 12