Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

the $_ Special Variable

by MiriamH (Novice)
on Jul 06, 2012 at 14:54 UTC ( #980288=perlquestion: print w/replies, xml ) Need Help??
MiriamH has asked for the wisdom of the Perl Monks concerning the following question:

I am just beginning to learn Perl and I have seen a lot of code using the $_ variable. When is it useful to use in code?

Replies are listed 'Best First'.
Re: the $_ Special Variable
by zentara (Archbishop) on Jul 06, 2012 at 15:42 UTC
Re: the $_ Special Variable
by toolic (Bishop) on Jul 06, 2012 at 15:27 UTC
Re: the $_ Special Variable
by kennethk (Abbot) on Jul 06, 2012 at 15:14 UTC
    Depending on your coding style, $_ can be ubiquitous. It's a default loop variable and default input for a number of functions. See the link for some general use scenarios.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      And you can write your own function that takes an implicit $_ using the (_) prototype.

      My favourite use for $_ is when defining a function that accepts a coderef. Example

      # This is a fairly useless function which is basically # just a copy of grep which enforces numeric context # on the list items... # sub filter_nums (&@) { my $coderef = shift; return grep { $coderef->() } map { 0 + $_ } @_ } my @even = filter_nums { not($_ % 2) } qw(1 2 3 4 potato);
      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: the $_ Special Variable
by Anonymous Monk on Jul 06, 2012 at 16:04 UTC
Re: the $_ Special Variable
by aaron_baugher (Curate) on Jul 07, 2012 at 02:46 UTC

    Most of the time, you use $_ without actually using it -- without typing it, that is. Take this code:

    my @array; while(<$file>){ chomp; tr/A-Z//d; push @array, [split /\s+/]; }

    Each of those lines of code operates on $_, though you don't see the variable explicitly typed at all. That's because many Perl functions operate on $_ by default if they aren't given a specific argument.

    Some say using $_ is bad practice and makes code less maintainable. That may be true for longer loops containing many other variables, but for short loops like the above, in my opinion it's actually clearer than:

    my @array; while(my $line = <$file>){ chomp $line; $line =~ tr/A-Z//d; push @array, [split /\s+/, $line]; }

    Aaron B.
    Available for small or large Perl jobs; see my home node.

Re: the $_ Special Variable
by bulk88 (Priest) on Jul 07, 2012 at 01:54 UTC
    When to use $_?

    Ideally, never. What it contains? Who knows. Its as useful as a variable called "$scalar".

    Its most useful to JAPHs and one liners, and saving time in writing code for experienced programmers who don't care about maintainability or readability of their code.

    Some will argue to use it whenever possible because its one less variable to eat up space in a sub's pad.
      Some will argue to use it whenever possible because its one less variable to eat up space in a sub's pad.

      I've never heard that.

      Ideally, never.

      That rules out map and grep then.


      Improve your skills with Modern Perl: the free book.

        use strict; use Data::Dumper; use Devel::Peek; use B::Deparse; use B::Concise; use B 'svref_2object'; use Devel::Size qw(size total_size); sub printdef { foreach (@_){ chomp; } foreach(@_){ print; } } sub BtoReg{ my @a = (); foreach(@_){ if($_->isa("B::SPECIAL")){ print "SPECIAL ".$B::specialsv_name[$$_]."\n"; } else{ print "ptr ".$$_."\n".Dumper($_->object_2svref()); } } } print Dumper(%B::SPECIAL::); print "\n\n PRINTDEF\n\n"; my $cv = svref_2object(\&printdef); print $cv; print "padlist fill ".$cv->PADLIST->FILL()."\n"; my @arr = $cv->PADLIST->ARRAY(); my @a2 = $arr[0]->ARRAY(); print "first PAD ARR\n"; print Dumper([BtoReg(@a2)]); @a2 = $arr[1]->ARRAY(); print "second PAD ARR\n"; print Dumper([BtoReg(@a2)]); sub printmy { for my $line (@_){ chomp $line; } for my $line2 (@_){ print $line2; } } print "\n\n PRINTMY\n\n"; $cv = svref_2object(\&printmy); print $cv; print "padlist fill ".$cv->PADLIST->FILL()."\n"; @arr = $cv->PADLIST->ARRAY(); @a2 = $arr[0]->ARRAY(); print "first PAD ARR\n"; print Dumper([BtoReg(@a2)]); @a2 = $arr[1]->ARRAY(); print "second PAD ARR\n"; print Dumper([BtoReg(@a2)]); print "\n\nprintdef ".size(\&printdef )."\n\n"; print "\n\nprintmy ".size(\&printmy )."\n\n"; print "\n\nprintdef\n\n"; my $walker = B::Concise::compile('-src','-exec',\&printdef); $walker->(); print "\n\nprintmy\n\n"; $walker = B::Concise::compile('-src','-exec',\&printmy); $walker->();
        dan's custom devel size at C:/perl512/lib/XSLoader.pm line 94. $VAR1 = "ISA"; $VAR2 = *B::SPECIAL::ISA; PRINTDEF B::CV=SCALAR(0x1409f44)padlist fill 1 first PAD ARR SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef $VAR1 = [ "" ]; second PAD ARR ptr 21166580 $VAR1 = []; ptr 3767036 $VAR1 = \*::_; ptr 8557092 $VAR1 = \undef; ptr 8557044 $VAR1 = \undef; ptr 3767036 $VAR1 = \*::_; ptr 21167812 $VAR1 = \undef; ptr 3767036 $VAR1 = \*::_; ptr 3767036 $VAR1 = \*::_; ptr 21167748 $VAR1 = \undef; ptr 3767036 $VAR1 = \*::_; ptr 3767036 $VAR1 = \*::_; $VAR1 = [ "" ]; PRINTMY B::CV=SCALAR(0x1484984)padlist fill 1 first PAD ARR SPECIAL &PL_sv_undef ptr 21128756 $VAR1 = \"\$line"; SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef ptr 21128612 $VAR1 = \"\$line2"; SPECIAL &PL_sv_undef SPECIAL &PL_sv_undef $VAR1 = [ "" ]; second PAD ARR ptr 21128228 $VAR1 = []; ptr 21128724 $VAR1 = \undef; ptr 3767036 $VAR1 = \*::_; ptr 21128708 $VAR1 = \undef; ptr 21128660 $VAR1 = \undef; ptr 21128596 $VAR1 = \undef; ptr 3767036 $VAR1 = \*::_; ptr 21128548 $VAR1 = \undef; $VAR1 = [ "" ]; printdef 1620 printmy 1587 printdef B::Concise::compile(CODE(0x8292c4)) # 10: foreach (@_){ 1 <;> dbstate(main -2 C:\Documents and Settings\Owner\Desktop\pmpad.p +l:10) v:*,&,$ 2 <0> pushmark sM 3 <#> gv[*_] s 4 <1> rv2av[t2] sKRM/3 5 <#> gv[*_] s 6 <{> enteriter(next->a last->d redo->7) lKS/8 b <0> iter s c <|> and(other->7) vK/1 # 11: chomp; 7 <;> dbstate(main -3 C:\Documents and Settings\Owner\Desktop\pmp +ad.pl:11) v:*,&,$ 8 <#> gvsv[*_] s 9 <1> schomp[t5] vK/1 a <0> unstack v goto b d <2> leaveloop vK/2 # 13: foreach(@_){ e <;> dbstate(main 0 C:\Documents and Settings\Owner\Desktop\pmpad.pl +:13) v:*,&,$ f <0> pushmark sM g <#> gv[*_] s h <1> rv2av[t8] sKRM/3 i <#> gv[*_] s j <{> enteriter(next->o last->r redo->k) lKS/8 p <0> iter s q <|> and(other->k) K/1 # 14: print; k <;> dbstate(main -1 C:\Documents and Settings\Owner\Desktop\pmp +ad.pl:14) v:*,&,$ l <0> pushmark s m <#> gvsv[*_] s n <@> print vK o <0> unstack s goto p r <2> leaveloop K/2 s <1> leavesub[1 ref] K/REFC,1 printmy B::Concise::compile(CODE(0x1426694)) # 44: for my $line (@_){ t <;> dbstate(main 14 C:\Documents and Settings\Owner\Desktop\pmpad.p +l:44) v:*,&,$ u <0> pushmark sM v <#> gv[*_] s w <1> rv2av[t3] sKRM/3 x <{> enteriter(next->11 last->14 redo->y)[$line:12,14] lKS/LVINTRO 12 <0> iter s 13 <|> and(other->y) vK/1 # 45: chomp $line; y <;> dbstate(main 13 C:\Documents and Settings\Owner\Desktop\pmp +ad.pl:45) v:*,&,$ z <0> padsv[$line:12,14] lRM 10 <1> schomp[t4] vK/1 11 <0> unstack v goto 12 14 <2> leaveloop vK/2 # 47: for my $line2 (@_){ 15 <;> dbstate(main 17 C:\Documents and Settings\Owner\Desktop\pmpad.p +l:47) v:*,&,$ 16 <0> pushmark sM 17 <#> gv[*_] s 18 <1> rv2av[t7] sKRM/3 19 <{> enteriter(next->1e last->1h redo->1a)[$line2:15,17] lKS/LVINTRO 1f <0> iter s 1g <|> and(other->1a) K/1 # 48: print $line2; 1a <;> dbstate(main 16 C:\Documents and Settings\Owner\Desktop\pmp +ad.pl:48) v:*,&,$ 1b <0> pushmark s 1c <0> padsv[$line2:15,17] l 1d <@> print vK 1e <0> unstack s goto 1f 1h <2> leaveloop K/2 1i <1> leavesub[1 ref] K/REFC,1
        strangely the my version is smaller than the $_ version according to Devel::Size but you can see the pad names are gone.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://980288]
Approved by kennethk
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2017-12-14 23:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (414 votes). Check out past polls.

    Notices?