Search code examples
perlif-statementwhile-loopforeachiteration

Perl: foreach line, split, modify the string, set to array. Opendir, next if files=modified string. Unlink files


I'm having issues with the following block of code: Where $output is netstat -lnt | grep ":::60". Specifically the section under the comment #Create filename format

my @lines = split /^/, $output;
foreach my $line (@lines) {
 my ($garb, $long_ports)  = (split /\s*:::\s*/, $line);

#Get the last 2 digits of the 60XX port number
 my ($garb2, $ports) = (split /60/, $long_ports);

#Split values to numbers 0-9 for correct filename format
if ($ports < 10) {
  my ($garb3, $ports2) = (split /0/, $ports);

#Add 0 since 0 port is split to empty string
if (length($ports2) == 0){
  $ports2 = "0$ports2";
}

#Create file name format
my @locked_ports = ".X$ports2-lock";
 }
}
 my %h = map {$_ => 1 } @locked_ports;
 #open /tmp and find the .X*-lock files that DO NOT match locked_ports
 opendir (DIR, $tmp ) or die "Error in opening dir $tmp\n";
 while (my $files = readdir(DIR)) {
   if (exists $h{$files}){
   next}
   unlink $files;
 }
   closedir(DIR);

I've also tried:

#Create file name format
my @locked_ports = ".X$ports2-lock";
 }
}
 #open /tmp and find the .X*-lock files that DO NOT match locked_ports
 opendir (DIR, $tmp ) or die "Error in opening dir $tmp\n";
 while (my $files = readdir(DIR)) {
   next if $files =~ @locked_ports;
   unlink $files;
 }
   closedir(DIR);

And:

#Create file name format
my $locked_ports = ".X$ports2-lock";
 }
}
 #open /tmp and find the .X*-lock files that DO NOT match locked_ports
 opendir (DIR, $tmp ) or die "Error in opening dir $tmp\n";
 while (my $files = readdir(DIR)) {
   next if $files =~ $locked_ports;
   unlink $files;
 }
   closedir(DIR);

Each time I get an error similar to: Global symbol "@locked_ports" requires explicit package name, Global symbol "$locked_ports" requires explicit package name

How can I have the while "next" over filenames that equal the lines of locked_ports?

Any help much appreciated.

Thanks.


Solution

  • my scopes the variable to the inner-most block (curlies) in which it is located.

    {
       my $foo;
       ...
    }
    
    # $foo not accessible here.
    

    The block ends on the line after the one where you create the variable. Move the variable's declaration so it has a sufficiently large scope.