Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Turning foreach into map?

by polettix (Vicar)
on Apr 05, 2005 at 09:55 UTC ( #444917=note: print w/replies, xml ) Need Help??


in reply to Re^2: Turning foreach into map?
in thread Turning foreach into map?

Arguments are passed "by reference" in perl subs, allowing in-place modification. So, you can do things like the following:
sub double_it { $_[0] *= 2 } my $x = 1; print "\$x is $x\n"; double_it($x); print "\$x is now $x\n";
and have
$x is 1 $x is now 2
When you use:
my ($url, @list) = @_;
you're creating copies of the input arguments, so when you modify them you don't have any side-effect outside the function. In your code, these copies are inefficient and not needed, because the code is quite simple and you don't perform in-place modifications. So, you simply grab the first parameter, and use the resulting @_ instead of @list, saving space and time:
sub links { my $url = shift; # This removes the first element of @_ map { "$url/$_" } @_; # You don't need return :) }
I also find this construct useful when porting functions into classes. When you transform a plain function in a class/object method, the first parameter that's passed is the class name/reference to object, so if you have a function:
sub some_func { # ... some stuff? my ($foo, $bar, $baz) = @_; # ... other stuff }
you can transform it at once:
sub some_func { my $self = shift; # Maybe do some checks with $self first? # ... some stuff? my ($foo, $bar, $baz) = @_; # ... other stuff }
in a much cut-and-paste fashion. But do check the code!

Flavio (perl -e "print(scalar(reverse('ti.xittelop@oivalf')))")

Don't fool yourself.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2023-02-04 21:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (31 votes). Check out past polls.

    Notices?