in reply to Re: (Perl 5.10.1 or before)What does $_ refer to here?
in thread (Perl 5.10.1 or before)What does $_ refer to here?

how would I use $line directly in the while condition? And what makes that better than declaring it as I did? Also, if I left $_ as it is in the second, strictured code block, it would refer to the same $_ as the first block of code, right? Because you're saying that the $_ refers to the iterator in "foreach". I apologize for parroting back what you're saying. I'm a perl novice, and this helps me solidify information.

Replies are listed 'Best First'.
Re^3: (Perl 5.10.1 or before)What does $_ refer to here?
by Athanasius (Archbishop) on Jun 10, 2019 at 13:32 UTC

    Hello hghosh,

    how would I use $line directly in the while condition? And what makes that better than declaring it as I did?

    I think LanX is recommending something along these lines:

    while (my $line = <IN>) { chomp $line; ...

    which is simpler and clearer.

    Also, if I left $_ as it is in the second, strictured code block, it would refer to the same $_ as the first block of code, right?

    Not sure which blocks you’re referring to; but, just to be clear, $_ refers to the “current” (i.e., the most closely related) syntactic construct that sets it. For example:

    use strict; use warnings; for ('A' .. 'C') { print "Outer: \$_ = $_\n"; for (10 .. 12) { print " Inner: \$_ = $_\n"; } print "Outer: \$_ = $_\n"; }

    produces:

    23:21 >perl 2004_SoPW.pl Outer: $_ = A Inner: $_ = 10 Inner: $_ = 11 Inner: $_ = 12 Outer: $_ = A Outer: $_ = B Inner: $_ = 10 Inner: $_ = 11 Inner: $_ = 12 Outer: $_ = B Outer: $_ = C Inner: $_ = 10 Inner: $_ = 11 Inner: $_ = 12 Outer: $_ = C 23:22 >

    — showing that there are actually as many independent instances of $_ (two, in this case) as the scoping requires.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^3: (Perl 5.10.1 or before)What does $_ refer to here?
by LanX (Saint) on Jun 10, 2019 at 13:35 UTC
    Hi

    C&P on googling "default variable Perl":

    Perl has something similar to the pronoun "it" —a default variable that is the implied target of many operators and built-in functions in Perl. If you do not specify a variable, the functions and operators are executed on the default variable. That variable is $_, and it is the single most important variable in Perl.

    So it depends on the last relevant statement.

    Because this can get quickly messy with longer code it's good style to avoid it then by using explicit variables.

    You could write while ( my $line = <IN> ) { ...

    Hope it's clearer now :)

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

    Update

    See also Gabor's in depth explanation

    https://perlmaven.com/the-default-variable-of-perl