On Thursday 29 Apr 2010 19:25:05 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.
No, it does not:
[code]
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
sub wrapped_func
{
return ("One", "Two", "Three");
}
sub wrapping_func
{
print "\...@_ Before calling wrapped_func() : ", Dumper([...@_]);
my @wrapped_func_ret = wrapped_func();
print "\...@_ After calling wrapped_func() : ", Dumper([...@_]);
print "wrapped_func_ret: ", Dumper([...@wrapped_func_ret]);
}
wrapping_func("Arguments", "to", "the", "Wrapping", "Function");
[/code]
[output]
@_ Before calling wrapped_func() : $VAR1 = [
'Arguments',
'to',
'the',
'Wrapping',
'Function'
];
@_ After calling wrapped_func() : $VAR1 = [
'Arguments',
'to',
'the',
'Wrapping',
'Function'
];
wrapped_func_ret: $VAR1 = [
'One',
'Two',
'Three'
];
[/output]
As you can see, the value of @_ is not affected by the call to the wrapped
function.
> 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)
>
Just do:
my ($name) = Function1 ($arg);
This will evaluate Function1 in list context (instead of scalar or void
context) and only get the first element. But the @_ of a function is not
affected by calls to other functions inside it.
Regards,
Shlomi Fish
> Anything wrong with this method? If so, what's the correct method then?
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Why I Love Perl - http://shlom.in/joy-of-perl
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: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/