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 (Cardinal) 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.

A reply falls below the community's threshold of quality. You may see it by logging in.