tags:

views:

82

answers:

2

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.

+9  A: 

Just add some extra parentheses:

my $a = (split(/,/, $comma_separated))[0];
Sean
That was simple --- thanks.
Carl
Since in many cases the parenthesis are optional on function cals, I would usually write this as `my $x = (split /,/ => $str)[0]`
Eric Strom
@Carl, a way you might think of it is that for `split( ... )` the parentheses only address the *call* -> you want to call split with these arguments. Tacking a `[0]` onto that makes little sense. However `( split ... )` addresses the value *returned*, which is really what you want to index.
Axeman
+4  A: 

Just like you can do this:

($a, $b, $c) = @array;

You can do this:

my($a) = split /,/, $comma_separated;

my $a on the LHS (left hand side) is treated as scalar context. my($a) is list context. Its a single element list so it gets just the first element returned from split.

It has the added benefit of auto-limiting the split, so there's no wasted work if $comma_separated is large.

Schwern
Perl already performs this optimization automatically. From "perldoc -f split": "When assigning to a list, if LIMIT is omitted, or zero, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work."
Sean
Oh neat, I had no idea! Seems its always done that.
Schwern