in reply to Placement of Subs
OTOH, if you put your call to the sub at the end of the file, transforming your sub into a "top" sub, then you face the problem of unintended globals that Juerd is referring to. In the following case, your "dosomething" will work as expected, unless you call "dosomethingelse" first, in which case your lexical variable gets changed.#!/usr/bin/perl -w use strict; dosomething(); my $stuff = "ABCD"; # bottom sub sub dosomething { print "$stuff\n"; }
Most of the problems that you might have with subs are related to using globals (or lexically scoped that act like globals) or not.#!/usr/bin/perl -w use strict; my $stuff = "ABCD"; # visible to all subs from now on #top subs { # start closure my $privatestuff = "WOW!"; #visible only from dosomething sub dosomething { print "$stuff \t $privatestuff\n"; } } # end closure sub dosomethingelse { $stuff = "WXYZ"; } dosomething();
My personal recommendation is: if you have a lot of subs, consider making a module out of them.#!/usr/bin/perl -w use strict; dosomething("ABCD"); #top subs sub dosomething { my $arg = shift; print "$arg\n"; } dosomething "EFGH";
_ _ _ _ (_|| | |(_|>< _|
|
---|