Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Builtin functions defaulting to $_

by ikegami (Patriarch)
on Mar 23, 2007 at 15:51 UTC ( [id://606271]=note: print w/replies, xml ) Need Help??


in reply to Builtin functions defaulting to $_

How to make your own function that defaults to $_:

sub myfunc { my $arg = @_ ? $_[0] : $_; for ($arg) { ... } }

The for is a convenient way to alias $_. (local $_ is buggy. It doesn't work well if $_ is tied or aliased to someting that's tied, and it doesn't protect pos($_).) Of course, you could just work with $arg directly instead of aliasing $_ to it.

The use of a lexical ($arg) allows us to modify $_ without affecting the argument in the caller. If you don't modify $_, the above can be simplified to

sub myfunc { for (@_ ? $_[0] : $_) { ... } }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-20 03:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found