in reply to Global, Local, what the..?

I don't think I understand the previous answers.

To me, the crux is that when you pass scalars to a subroutine, @_ actually contains aliases to the scalars themselves so that modifying $_[0] directly actually modifies the caller's scalar. Similarly, modifying $_ in a map, for, or foreach actually modifies the elements of the list that you are looping over.

So $_ is an alias for $_[0] which is an alias for the caller's $value and $value gets modified in-place and the return value doesn't matter because you call the function in a void context and the return value is thrown away.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
(Ovid - subroutine return example w/map)
by Ovid (Cardinal) on Dec 15, 2000 at 03:26 UTC
    tye: I think you're confusion stems from our bad examples :)

    You are right in your assessment, but the code below should clarify this. Because we're localizing arguments to the sub, you can see how it returns the last evaluated statement. The code below will print "his hat" (without the quotes):

    use strict; my @list = qw( this that foo bar ); print join ' ', mungeIt( @list ); sub mungeIt { my @localList = @_; my @stuff = map { s/th/h/ ? $_ : () } @localList; }

    Cheers,
    Ovid

    Update: Oh! I misunderstood tye's question, but clarified the answer. Oh well. All's well that ends well.

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      FYI, I understood that return is optional and that a subroutine will return the value of the last statement executed. I just didn't see what that had to do with the original question. I mean, antjock asked several questions about the lack of the return and return values, but I thought the real question was "why does this work?" and I didn't think anyone had answered that... and I wasn't sure I was just missing something (I can be slow some days). (:

              - tye (but my friends call me "Tye")