--- Ben Curran <[EMAIL PROTECTED]> wrote:
> Trying to alter the value of $testfile depending on how many arguments are
> given, using the following:
>
> if (@ARGV == 2) {
> chdir $ARGV[0];
> my $testfile = $ARGV[1];
> }
> else {
> my $testfile = $ARGV[0];
> }
This is syntactically correct, but still fails to do what you expect because of
"scope". The
scope of a variable (or statement) can often be difficult to tell without proper
indenting, so
let's fix that up:
if (@ARGV == 2)
{
chdir $ARGV[0];
my $testfile = $ARGV[1];
}
else
{
my $testfile = $ARGV[0];
}
There are many different ways to indent, but I chose a style that seemed similar to
what you were
using, is clean, and also demonstrates this problem well. Good indentation is not
always a
guarantee of a good programming, but poor indentation is almost always indicative of
programming
problems.
Lexically scoped variables (those declared with the 'my' keyword) have a scope that is
confined to
the block they are declared in. A block can loosely be defined as a section of the
program that
is delimited by curly braces {}. As you can see in your example above, you have
declared
$testfile within braces. It won't exist outside of them. Your next example, which
you said
works, looks like this when we clear up the indentation:
my $testfile;
if (@ARGV == 2)
{
chdir $ARGV[0];
$testfile = $ARGV[1];
}
else
{
$testfile = $ARGV[0];
}
You can see that $testfile has been declared *outside* of those blocks. Also, note
that a
variable that gets declared is also visible to blocks within its declared scope:
sub foo
{
my $bar = shift;
my $baz = 0;
if ( $bar > 7 )
{
$baz += 3;
}
else
{
$baz = "Ovid comes up with bad examples";
}
return $baz;
}
Hope that helps.
Cheers,
Curtis "Ovid" Poe
=====
"Ovid" on http://www.perlmonks.org/
Someone asked me how to count to 10 in Perl:
push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//;
shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A
__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]