0

I went through a couple of discussions to find the solution but none of them seem to be working in my case.

I have the following piece of code

print ("Choose from the following\n");
print ("op1 op2\n");

my $x = <>;  
chomp($x);     
print ("x is $x");

if ($x eq "op1")
{
my $DirA = "./A";
my $DirB = "./B"; # **I want to use this dirA and dir B below (Tried switch stmts but I 
#**get the same error)**
}

opendir my($dh), "$DirA" or die "Couldn't open dir DirA!";
my @files = readdir $dh;
closedir $dh;
system("rm -rf diffs");
system ("mkdir diffs\n");
foreach my $input (@list) {
.
.
.
}

I get this error: Global symbol "$DirA" requires explicit package name at test_switch.tc

Can someone please help me with the same. My intension is to add options/switches to my script.. Like "test.pl -A", "test.pl -B" for which I started with a case stmt. Please provide inputs on this.

Rancho
  • 309
  • 4
  • 12
  • Can you use perl modules? If so, I suggest you consider using [Getopt::Long](http://search.cpan.org/~jv/Getopt-Long-2.39/lib/Getopt/Long.pm). It will make your life a little easier. – David Apr 10 '13 at 00:17

2 Answers2

2

Your $DirA and $DirB are not global, they are only defined in the scope of the if statement in which they're declared with a my. In general, from the documentation: "A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval." To use them in any code that follows, you'll have to do something like:

my $DirA;
my $DirB;

if ($x eq "op1") {
  $DirA = "./A";
  $DirB = "./B";
} else {
  $DirA = ...
  $DirB = ...
}

Note the else: you should also do something if $x is not "op1" because as it stands even if the code had run you'd have gotten an error when trying to pass an undefined value to opendir.

miorel
  • 1,863
  • 2
  • 14
  • 18
  • Thanks. Now I am getting this error after adding that if ($x eq "op1"){ my $DirA = "./A"; my $DirB = "./B"; } else{ my $DirA = "./C"; my $DirB = "./D"; } opendir my($dh), "$DirA" or die "Couldn't open dir DirA!"; Use of uninitialized value in string at test_switch.tc line 47, <> line 1. Couldn't open dir DirA! at test_switch.tc line 47, <> line . This is the opendir line – Rancho Apr 10 '13 at 00:30
  • Don't put `my` inside the `if` and `else`. This will mask the variables with the same name defined outside the block. To make sure things are ok, `print "DirA = $DirA and DirB = $DirB\n"` before the `opendir`. – miorel Apr 10 '13 at 00:45
2

Just declare the variables before the if block and they will be accessible thereafter.

my $DirA;
my $DirB;

if ($x eq "op1") {
    $DirA = "./A";
    $DirB = "./B";
}
Borodin
  • 126,100
  • 9
  • 70
  • 144