Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Returning first element of an array from a function

by davido (Cardinal)
on Mar 17, 2004 at 07:47 UTC ( [id://337246]=note: print w/replies, xml ) Need Help??


in reply to Returning first element of an array from a function

In the case you provided, you would do something like this:

( $foo ) = split ( /\./, $bar );

By wrapping the left hand side in parens, you put the assignment into list context, and the first element of that list is stored in $foo.

For more complex cases, sometimes its helpful to wrap the right-hand-side in parens, and then index into the element that you want returned:

$foo = ( split ( /\./, $bar ) )[0];

The latter method would allow you to return several elements at once. You could even do this:

( $foo, $boo ) = ( split ( /\./, $bar ) )[ 1, 0 ];

...which would return the 2nd element to $foo, and the 1st element to $boo.


Dave

Replies are listed 'Best First'.
Re: Re: Returning first element of an array from a function
by biosysadmin (Deacon) on Mar 17, 2004 at 07:50 UTC
    I actually prefer to do the following for the sake of readability:
    ($foo,undef) = split( /\./, $bar );
    That way I explicitly throw away the rest of the list instead of discarding it implicitly.
      ($foo,undef) = split( /\./, $bar );
      That way I explicitly throw away the rest of the list instead of discarding it implicitly.

      You're not explicitly throwing away the rest of the list... you're just explicitly ignoring the second element returned and then non-explicitly ignoring the rest of it. Using undef to ignore returned elements is only useful if you're going to capture something after the undef'ed element (ie: ($foo, undef, $bar) = split(/\./, $baz); or (undef, $foo) = split(/\./, $bar);).

        TIMTOWTDI of course:

        # this: ($foo, undef, $bar) = split(/\./, $baz); # can also be done as: ($foo, $bar) = (split(/\./, $baz))[0,2]; # and this: (undef, $foo) = split(/\./, $bar); # can also be done as: ($foo) = (split(/\./, $bar))[1];

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://337246]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2024-04-24 13:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found