Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: unexpected: inside sub($1,$2) if do // then arguments will be changed

by ikegami (Patriarch)
on Sep 12, 2011 at 05:05 UTC ( [id://925405]=note: print w/replies, xml ) Need Help??


in reply to unexpected: inside sub($1,$2) if do // then arguments will be changed

perlvar says "read-only and dynamically scoped"

They are. mysub does indeed back them up on entry and restore them on exit.

$ perl -E' sub f { say $1; "b"=~/(b)/; say $1; } "a"=~/(a)/; say $1; f(); say $1; ' a a b a

The problem is that $_[0] and $_[1] are aliased to $1 and $2, so changing $1 and $2 changes $_[0] and $_[1].

$ perl -E' sub f { say $_[0]; "b"=~/(b)/; say $_[0]; } "a"=~/(a)/; f($1); ' a b

Three solutions:

  • /.../; mysub("$1", "$2"); sub mysub { /.../; shift; shift; }
  • my ($x, $y) =~ /.../; mysub($x, $y); sub mysub { /.../; shift; shift; }
  • /.../; mysub($1, $2); sub mysub { my ($x, $y) = @_; /.../; $x; $y; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 16:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found