Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: My very confusing questions

by davido (Cardinal)
on Jul 08, 2014 at 05:40 UTC ( [id://1092676]=note: print w/replies, xml ) Need Help??


in reply to My very confusing questions

It would help if you posted the code that you have a question about. What you posted doesn't do what you claim. It stringifies a sub reference, turning it into a hash key that indexes a subref as its value, and follows that up by stringifying another subref which becomes a hash key that indexes an undefined value. If warnings are enabled, it also produces one of those. There is just too much missing from the code you showed us, and what you did show us doesn't actually work... we won't be able to help with that part of the question until you fix things.

If your question is what does shift do in a subroutine, you already mostly answered it yourself.

shift shifts the lowest-indexed element off of an array, and returns that element as its return value. Inside a subroutine, the implicit array that shift operates on is @_. Inside of a subroutine, @_ contains the parameters that were passed to the sub when it is called. Therefore:

sub add { return shift() + shift(); }

...is about the same as...

sub add { return $_[0] + $_[1]; } # ...or... sub add { my ( $left, $right ) = @_; return $left + $right; }

The biggest difference being that the first and third examples disassociate the values from the caller, so that they are not aliased back to the caller.

As for what return does, well, subroutines are able to return a value to their caller. For example:

my $size = length( $some_string );

If I needed to write my own length function, here is one way to do it:

sub mylength { my $string = shift; my $size = $string =~ tr///c; # Don't worry how it works. return $size; } # Invoke it like this: my $length = mylength("Hello world."); # $length now holds 12.

return is how we tell a subroutine explicitly what value to return. Perl has another feature that dictates that if there is no explicit return statement, the last expression to be evaluated becomes the subroutine's return value. Relying on that feature is useful for really small subroutines, but for anything non-trivial can lead to confusion. So we nearly always use return for anything that isn't absolutely clear otherwise.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-03-19 07:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found