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

Builtin functions defaulting to $_

by ambrus (Abbot)
on Mar 23, 2007 at 13:52 UTC ( #606237=perlmeditation: print w/ replies, xml ) Need Help??

Here's a list of perl builtins that default to act on $_ when given no argument.

  • filetest operators (except for -t)
  • abs
  • alarm
  • chomp
  • chop
  • chr
  • chroot
  • cos
  • defined
  • eval
  • evalbytes
  • exp
  • glob
  • hex
  • int
  • lc
  • lcfirst
  • length
  • log
  • lstat
  • mkdir (since perl 5.10.0)
  • oct
  • ord
  • pos
  • print
  • quotemeta
  • readlink
  • ref
  • require
  • reverse (Update: only in scalar context)
  • rmdir
  • sin
  • split (actually defaults to $_ on its second argument, ' ' on first one)
  • sqrt
  • stat
  • study
  • uc
  • ucfirst
  • unlink (the scaryest)
  • unpack (since perl 5.10.0, the second argument defaults to $_)

There are other operations that use $_ implicitly. For example, regexps, substitutions, and transliterations (m, s, tr, y) act on $_ unless a different string is given by the =~ operator; map, grep, the for statement modifier, and for loops without explicit loop variable specified use $_ as the loop variable; a diamond operator in a while loop stores the line to $_.

Below are some functions that do not default to $_.

Note that a few functions behave differently if they are called with an empty pair of parenthesis (usually taken as an empty list).

  • -t (terminal) filetest: defaults to STDOUT
  • bless: requires an argument
  • caller: returns less information without argument
  • chdir: uses the home directory
  • die: defaults to $@ (to rethrow an exception caught with eval) or a generic message: "Died"
  • do: syntax error without parenthesis; with empty parenthesis, dies with "Null filename used"
  • eof: with empty parenthesis defaults to ARGV, without parenthesis defaults to the last file read (but detects the ends of individual files read by ARGV)
  • exec: it seems that the call just returns failure, I can't find anything in the docs
  • exit: defaults to zero
  • gethostbyname, getnetbyname, getprotobyname: requires an argument
  • getpgrp: uses zero, meaning the current process
  • getpwnam, getgrname: requires an argument
  • getpwuid, getgrgid: requries an argument
  • gmtime: uses current time
  • local: syntax error without parenthesis; with empty parenthesis, is a no-op (localizing $_ could be useful, but this way is more consistent with localizing lists of variables)
  • localtime: uses the current time
  • lock: requires an argument
  • mkdir: required an argument before perl 5.10.0
  • my: requires an argument (even empty parenthesis don't suffice)
  • our: requires an argument
  • pack: requires an argument
  • prototype: seems to just return undef, I've found nothing in the docs
  • rand: uses 1
  • readpipe: no idea, but it can produce segfaults
  • reset: resets only question-mark searches, no variables
  • return: returns empty list in list context, undef in scalar context
  • scalar: requires an argument
  • sleep: sleeps forever
  • sort: gives a funny error message without parenthesis; with parenthesis, sorts the empty list
  • sprintf: requires an argument
  • srand: uses some reasonable seed
  • syscall: requires an argument
  • system: seems to just return an exit code 255, I've found nothing relevant in the docs
  • tied: requires an argument
  • umask: returns the current umask without changing it
  • undef: returns undef without undefining anything
  • untie: requires an argument
  • waitpid: requires two arguments
  • warn: uses $@ suffixed with "\t...caught", or a sensible message "Warning: something's wrong" if $@ is unset.
  • write: uses the currently selected filehandle

The following functions accept a filehandle, directory handle, label, or bareword as an argument, and thus don't default to $_. (I do not list those functions that need an array or hash argument, like pop.)

  • binmode: requires an argument
  • close: defaults to the selected filehandle
  • closedir: requires an argument
  • dump: defaults to the top of the program
  • fileno: requires an argument
  • getc: uses STDIN
  • getpeername, getsockname: requires an argument
  • goto: requires an argument
  • last, next: uses the innermost loop
  • no: requires an argument
  • open: requires an argument
  • package: without argument, declares that there is no current package, but this usage is strongly depreciated
  • readdir: requires an argument
  • readline: no idea, I could even get a segfault (the diamond shortcut, however, defaults to the special ARGV filehandle)
  • redo: uses the innermost loop
  • rewinddir: requires an argument
  • select: returns the current selected filehandle without changing it
  • tell: uses the filehandle last read
  • telldir: requires an argument
  • use: requires an argument

I've compiled these lists using both the perldoc perlfunc and testing how the functions actually behave with perl (5.8.8 i686-linux). For this reason, there can be errors and omissions in this list. If you know about any omission, please contact me.

Update: added readmore.

Update 2012-12-27: added the new evalbytes function.

Update 2014-01-29: added changes to mkdir and unpack.

Comment on Builtin functions defaulting to $_
Re: Builtin functions defaulting to $_
by Mutant (Priest) on Mar 23, 2007 at 14:56 UTC
    Some things in this list might change in 5.10 (at least mkdir() will). Who knows when that might come out tho :)
      The list will certainly change for Perl 6, insofar as it will be an empty list. If you want to default a function call to $_ you use the "unary dot" form:
      for 1..10 { .say }
      Of course, pattern matching and topicalizers still implicitly deal with $_, but you no longer have to memorize a long list of functions, nor worry about the difference between
      rand > 0.5 # means rand($_) > 0.5 rand < 0.5 # parse error looking for fileglob
      since in Perl 6 that is unambiguously
      .rand < 0.5 # always means rand($_) < 0.5
      You don't have to memorize which symbols are true globals either. As for Perl 5's magical use of $a and $b, the less said the better... :-)
        You don't have to memorize which symbols are true globals either.
        which will relieve a lot of grief. Like with $! and $@ which may get overwritten if not dealt with in a timely manner. If I well remember, $! will be just a reference to what the current error looks like; therefore the question: what's $@ in Perl 6, if it exists at all? I could think of that as a list of messages of what things blew up from there to here (ie some "exception stack trace excerpt") - but then, that would be more appropriately @$! (in perl5 syntax, that is)...

        update: reading again, not "have(ing) to memorize which symbols are true globals" means: there are no true global symbols, right?

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Builtin functions defaulting to $_
by ikegami (Pope) on Mar 23, 2007 at 15:51 UTC

    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] : $_) { ... } }
Re: Builtin functions defaulting to $_
by brian_d_foy (Abbot) on Mar 24, 2007 at 03:04 UTC

    I went through perlfunc during a plane trip and tried to sort the functions and classify them. This is as far as I ever got, and I didn't go back over it to make sure I got it right or to see if I could sort them into better categories.

    No default

    different action without arg

    Misc

    $_

    optional args

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
Re: Builtin functions defaulting to $_
by Steve_p (Priest) on Mar 25, 2007 at 13:49 UTC

    Actually, just yesterday there was a new addition to the list, readpipe.

    Change 30747 by rgs@benny on 2007/03/24 16:46:02 Make readpipe default to $_

    Of course, you'll need to wait a bit for Perl 5.10 before you can use it.



    Test your modules with bleadperl!

      rsync -avz rsync://public.activestate.com/perl-current/ .
      ./Configure -des -Dusedevel -Dprefix=/path/to/test/perl
      make test
      make install
    

    Now, please test you modules! If you have test failures that don't happen with Perl 5.8.8, send a simplified test case to

    perlbug at perl.org

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://606237]
Approved by kyle
Front-paged by planetscape
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2015-07-02 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (25 votes), past polls