Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing directly into returned array in Perl

Tags:

perl

This question has been asked about PHP both here and here, and I have the same question for Perl. Given a function that returns a list, is there any way (or what is the best way) to immediately index into it without using a temporary variable?

For example:

my $comma_separated = "a,b,c";
my $a = split (/,/, $comma_separated)[0]; #not valid syntax

I see why the syntax in the second line is invalid, so I'm wondering if there's a way to get the same effect without first assigning the return value to a list and indexing from that.

like image 326
Carl Avatar asked Jul 01 '10 00:07

Carl


People also ask

How do I index an array in Perl?

Also, first will exit the implicit loop upon finding the index that matches. The grep equivalent would be $idx = grep { $array[$_] eq 'whatever' and last } 0 ..

How do I return an array in Perl?

return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.

What is $# in Perl?

$#array is the subscript of the last element of the array (which is one less than the length of the array, since arrays start from zero). Assigning to $#array changes the length of the array @array, hence you can destroy (or clear) all values of the array between the last element and the newly assigned position.

How do you access each element of an array in Perl?

To access a single element of a Perl array, use ($) sign before variable name. You can assume that $ sign represents singular value and @ sign represents plural values. Variable name will be followed by square brackets with index number inside it. Indexing will start with 0 from left side and with -1 from right side.


1 Answers

Just use parentheses to define your list and then index it to pull your desired element(s):

my $a = (split /,/, $comma_separated)[0];
like image 159
Sean Avatar answered Oct 22 '22 07:10

Sean