10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

APPENDIX ■ PERL BASICS 311#!/usr/bin/perl -w# scope1.pl$record = 4;print "We're at record ", $record, "\ n";{}my $record;$record = 7;print "Inside the block, we're at record ", $record, "\ n";print "Outside, we're still at record ", $record, "\ n";This should tell you$ perl scope1.plWe're at record 4Inside the block, we're at record 7Outside we're still at record 4$Let’s look at how this program works. First, we set our global variable $record <strong>to</strong> 4.$record = 4;print "We're at record ", $record, "\ n";Now we enter a new block and create a new lexical variable. Important! This is completelyand utterly unrelated <strong>to</strong> the global variable $record as my() creates a new lexical variable. Thisexists for the duration of the block only, and has the undefined value.{my $record;Next, the lexical variable is set <strong>to</strong> 7, and printed out. The global $record is unchanged.$record = 7;print "Inside the block, we're at record ", $record, "\ n";Finally, the block ends, and the lexical copy ends with it. We say that it has gone out ofscope. The global remains, however, and so $record has the value 4.}print "Outside, we're still at record ", $record, "\ n";In order <strong>to</strong> make us think clearly about our programming, we will ask <strong>Perl</strong> <strong>to</strong> be strictabout our variable use. The statement use strict; checks that, among other things, we’vedeclared all our variables. We declare lexicals with the my() function. Here’s what happens ifwe change our program <strong>to</strong> use strict format:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!