pedrosaurio
pedrosaurio

Reputation: 4926

Get particular sub set of elements from an array returned by a function

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

Answers (3)

Zaid
Zaid

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;
  • Avoid using $a and $b as variable names. They are special package variables intended to be used inside sort blocks.

Upvotes: 3

blio
blio

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

RobEarl
RobEarl

Reputation: 7912

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

my (undef, $over, $flow) = split /:/, 'stack:over:flow';

Upvotes: 2

Related Questions