in reply to Re^7: How can I avoid code repetition here
in thread How can I avoid code repetition here

you do believe that my $str = "..."; chop $str modifies the lexical

Yes, with *explicit* passing of a lexical, it is easy to understand how it is done; and if the compiler "knows" about chop (as a 'builtin' function), I can understand now how this work for this case. I wonder whether it would also be possible to write a user defined sub which, when called without parameters, acts on $_ even if it was lexically declared. I don't see how this can be done...

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re^9: How can I avoid code repetition here
by JavaFan (Canon) on Oct 09, 2009 at 08:36 UTC
    sub hello (_) {say "Hello, ", @_ ? $_[0] : $_} hello "world"; my $_ = "mars"; hello; { my $_ = "earth"; hello; } hello; __END__ Hello, world Hello, mars Hello, earth Hello, mars

      I now see that you meant the case

      my $_; # lexical declared in outer scope sub f { # $_ used here.... }
      Sorry for my misunderstanding. But in this case, I don't see why my original code would not work for this case?

      -- 
      Ronald Fischer <ynnor@mm.st>
        You're missing the case where $_ is defined in an inner scope.

        Compare:

        sub f {say @_ ? $_[0] : $_} sub g (_) {say @_ ? $_[0] : $_} $_ = "outer"; { my $_ = "inner"; f; g; } __END__ outer inner
        Lacking the _ prototype, you original code would not work for the case of lexical $_ not in the same scope as the function definition.
Re^9: How can I avoid code repetition here
by Anonymous Monk on Oct 09, 2009 at 08:21 UTC
    What do you mean?
    $_ = 1; my $_ = 6; sub ford { $_ .= 6; }; warn $_; warn ford(); warn $_; warn $::_; __END__ 6 at - line 4. 66 at - line 5. 66 at - line 6. 1 at - line 7.