in reply to Implicit assignment to $_

This is a prime example of why I preach so heavily about use strict;. If you had invoked that pragma you'd have seen the warning:

Use of uninitialized value $_ in print at sopw-simple.pl line 6.
Quoting from Gabor Szabo on his website http://perl5maven.com/the-default-variable-of-perl:
In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used. In general, I'd say you should NOT see $_ in real code. I think the whole point of $_ is that you don't have to write it explicitly.

Well, except when you do.

Having a default variable is a very powerful idea, but using it incorrectly can reduce the readability of your code.
Just for grins I tried:
$_ = "TestA" or "TestB";
and Perl was not happy with that issuing:
Found = in conditional, should be == at ./sopw-simple.pl line 4. Useless use of a constant (TestB) in void context at ./sopw-simple.pl +line 4. TestA

My suggestion is read the web page I provided above for some hints on what you can and can't do with $_. Just a thought...


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: Implicit assignment to $_
by tobyink (Canon) on Feb 26, 2013 at 17:01 UTC

    "This is a prime example of why I preach so heavily about use strict;. If you had invoked that pragma you'd have seen the warning:

    "Use of uninitialized value $_ in print at sopw-simple.pl line 6."

    Nuh-uh... strict does no such thing.

    strict does three things:

    • Throws compile-time errors for undeclared variables.
    • Throws compile-time errors when barewords are seen which don't correspond to subs, and don't look like the package name in a class method call.
    • Throws run-time errors when symbolic references are used, or more generally when trying to dereference a variable which does not contain a reference.

    strict never issues any warnings. And strict doesn't care about variables being undef (unless you try to dereference them).

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
          Nuh-uh... strict does no such thing.

      Really? That's a copy/paste from my terminal. Wish there was a way to post screenshots to PM.


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

        You probably ran Perl with -w then, because it's warnings that produces that error.

        package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re^2: Implicit assignment to $_
by McA (Priest) on Feb 26, 2013 at 16:19 UTC

    Despite all correct (!!) advices given before:

    print for ("Test A" or "Test B");

    Best regards
    McA