I thought I had gotten a pretty good grasp of scoping and variables both from the various tutorials here, several classes on Perl and also the Camel Book. I was testing out a section of code that will manipulate a variable within a code block and I was thinking that I would not have to reassign it back to the original value when I was finished since I assign it once at the start of the main package. I proceeded to test this out with the following code snippet.
#! /usr/local/bin/perl -w
use strict;
my $hero="Batman";
my $car="Pinto";
my $year=sprintf("%04d", (localtime)[5]+1900);
BLOCK0:{ print "In the first block, \$hero is $hero and \$car is $car.
+\n"; }
BLOCK1:{ my $hero="Superman";my $car="Porsche";print "In next code blo
+ck \$hero is $hero and \$car is $car.\n"; }
BLOCK2:{ print "In next code block, \$hero is $hero and \$car is $car
+.\n"; }
BLOCK3:{ print "To start, \$year is $year\n";}
BLOCK4:{ my $year=--$year; print "We change \$year to $year\n"; }
BLOCK5:{ print "And now, \$year is $year\n"; }
__DATA__
In the first block, $hero is Batman and $car is Pinto.
In next code block $hero is Superman and $car is Porsche.
In next code block, $hero is Batman and $car is Pinto.
To start, $year is 2003
We change $year to 2002
And now, $year is 2002
According to everything I've seen, the last line should be: And now, $year is <b>2003</b>. Obviously, this is not the case and I am trying to figure out why this is so. I have also tried hardcoding a value into $year at the start and still get the same result. I am suspecting the decrement operator(?) is doing something to the value of $year in the main package, but what and how.
"Ex libris un peut de tout"
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.