Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Local

There is one more function that I'd like to draw to your attention, and we'll launch straight into the demonstration:

@words=@ARGV;

print "Output Field Separator is :$,:\n";
print '1. Words:', @words, "\n";

&change;

$,='_';

print "\nOutput Field Separator is :$,:\n";
print '2. Words:', @words, "\n";

&change;

sub change {
	print '   Words:', @words, "\n";
}

which should be executed something like this:

perl test.pl sarcasm is the lowest form of wit

The special variable $, defines what Perl should print in between lists it is given. By default, it is nothing. So the first two prints should have no spaces between the words. Then we assign '_' to $, so the next prints have underscores between the words.

If we want to use a different value for $, in the change subroutine, and not disturb the main value, we have a little problem. This problem cannot be solved by my because global variables like $, cannot at this time be lexically scoped. So, we could manually do it:

@words=@ARGV;

print "Output Field Separator is :$,:\n";
print '1. Words:', @words, "\n";

&change;

$,="_";

print "\nOutput Field Separator is :$,:\n";
print '2. Words:', @words, "\n";

&change;

sub change {
	$save=$,;
	$,='*';
	print '   Words:', @words, "\n";
	$,=$save;
}

That works, but it is messy. Perl has a special function for occasions of this nature, called local . An example of local in action:

@words=@ARGV;

print "Output Field Separator is :$,:\n";
print '1. Words:', @words, "\n";

&change;

$,="_";

print "\nOutput Field Separator is :$,:\n";
print '2. Words:', @words, "\n";

&change;

sub change {
        local $,="!-!";
	print '   Words:', @words, "\n";
}

You can try it with my instead but it won't work. I'm sure you'll try it anyway, I know you learn things the hard way otherwise you a) wouldn't be programming computers and b) wouldn't be using this tutorial to do it.

The local function works in a similar way to my , but assigns temporary values to global variables. The my function creates new variables that have the same name. The distinction is important, but the reasons require perl proficiency beyond the scope of this humble tutorial. In practice, the difference is: