Search code examples
perlwmic

Unable to get the error and check if it exist


I am trying to access a server and get its name but it is not available how can i deal with the error and continue with the rest of the script.If this command qx($srvername) returns an error i want to exit the for loop

my @s =qw(v200 pm363   wq280 );
foreach $a (@s){

  eval {
  my $srvername="wmic /node: '$a' computersystem get Name";
  my $opt = qx($srvername) ;

  if($!){ 
     next;
  }
 };


print "here$a\n";   
}

Solution

  • You need to declare the $opt variable outside of the eval block if you want to use it. You also need to do the next outside of the eval block.

    I've changed a bunch of things around your code.

    We now declare $opt and $srvername outside of the eval. It's better to scope the eval as small as possible, and creating a string will not fail.

    We then call the qx() inside of the eval, and assign $opt, which is scoped inside the foreach block. That way you can access it afterwards.

    If the qx fails, we die, which breaks out of the eval block. If you care about the error that qx threw, you can throw $?.

    After the eval we check $@, wich holds the eval error. If something is in there (probably our $? from the qx), we go to the next iteration.

    my @s = qw( v200 pm363 wq280 );
    foreach my $node ( @s ){
      my $opt;
      my $srvername = "wmic /node: '$node' computersystem get Name";
    
      eval {
        $opt = qx($srvername) or die $?;
      };
    
      next if $@;
    
      print "$node - opt\n";   
    }
    

    Note that I also renamed $a to $node. The variable name $a is reserved for sort along with $b. It's also a good idea to give your variables meaningful names that speak for themselves.