Hi all,

On Thursday 29 Apr 2010 19:35:52 Shawn H Corey wrote:
> Akhthar Parvez K wrote:
> > On Thursday 29 Apr 2010, Shlomi Fish wrote:
> >> Why are you assigning to variables inside @_? It's almost always a bad
> >> idea.
> >> 
> >> @_ is the function parameters' list. You should read the values from
> >> there (using "my ($param1, $param2, $param3) = @_;" or "my $param1 =
> >> shift;" (short for "shift(@_)")) and then possibly mutate them if they
> >> are references and return values from the function using return.
> > 
> > Well, I know that @_ is a list with arguments passed to the function. But
> > I thought it also stores the "return" values from a subroutine. eg:- If
> > Function1 returns "abc" and "pqr" and I want to catch only the first
> > return value ("abc" in this case), I could use the following line:
> > 
> > my ( $name ) = ( $_[0] ) = Function1( $arg ); (Thanks to John and Shawn
> > for correcting me with that)
> > 
> > Anything wrong with this method? If so, what's the correct method then?
> 
> It overwrites the first element of @_.  Use this instead:
> 
>    my ( $name ) = () = Function1( $arg );

Just a note, the "=()=" or "= () =" pseduo-operator (see:
http://www.catonmat.net/blog/secret-perl-operators/#goatse ) is primarily used 
to evaluate the right side in list context and then get the count of the 
elements of the list at the left. Like so:

[code]
my $str = "5 foo 6 bar 7 baz";
my $count =()= $str =~ /\d/g;
# $count is now 3.
[/code]

If you want to extract the first element out of the list of return values, 
then this works as well:

        my ($name) = Function1( $arg );

As opposed to:

        my $name = Function1( $arg );

Which evaluates Function1 in a scalar context.

On the other hand the goatse operator ("=()=") won't help if you forget the 
parentheses around the assigned-to variable name.

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Funny Anti-Terrorism Story - http://shlom.in/enemy

God considered inflicting XSLT as the tenth plague of Egypt, but then
decided against it because he thought it would be too evil.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to