in reply to Re^4: Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?
in thread Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?
This highlights the duality of my.#!/usr/bin/perl -w use strict; our $c = 2; print "Before: c=$c\n"; my $c = 1 unless $c; print "After: c=$c\n";
If you had actually run that, you should have got the compiler error:
because you had warnings on."my" variable $c masks earlier declaration in same scope at 492281.pl +line 6.
Let's do it line by line:
The global variable also known as $main::$c is formally declared (for strictness), and assigned the value 2.our $c = 2;
The value of $main::$c (2) is printed.print "Before: c=$c\n";
If the current $c variable is true, declare a lexical variable with the same name, and assign it the value 1. On the first (and here only) pass, $c is just shorthand for the global $main::$c, and it's value is 2, so the lexical assignment doesn't happen.my $c = 1 unless $c;
However, the lexical creation did! Until the lexical $c goes out of scope (in this case, at the end of the file), all instances of $c refer to this lexical variable, and not to the global $main::$c. To access $main::$c, the "long" name must be used, as the short name points to something different.
The value of the lexical $c is printed. However, since the assignment didn't happen, it's still undefined. And if you'd actually tried it, you would have seen this:print "After: c=$c\n";
just before the "After..." string was printed.Use of uninitialized value in concatenation (.) or string at 492281.pl + line 7.
To separate these issues, try changing my $c to my $d:
gives#!/usr/bin/perl -w use strict; our $c = 2; print "Before: c=$c\n"; my $d = 1 unless $c; print "After: d=$d\n";
Do you see why?Before: c=2 Use of uninitialized value in concatenation (.) or string at 492281.pl + line 7. After: d=
-QM
--
Quantum Mechanics: The dreams stuff is made of
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Have you netted a Perl Monk or Perl Pretender in 5 minutes or less?
by Anonymous Monk on Sep 15, 2005 at 21:52 UTC | |
by QM (Parson) on Sep 15, 2005 at 23:39 UTC | |
by itub (Priest) on Sep 16, 2005 at 05:34 UTC |