chriswh
chriswh

Reputation: 27

Perl - Value of variable not working in a condition

I created this function.

When I print my variable my $bios_current, it shows $VAR1 = '200'; But my condition if ( $bios_current->responseCode() ne 200) considers that it is not 200.

Could you help me ? Is it a type problem ?

sub check_thermalshutdown_settings {
  my $host = shift;
  if ($host->get_property('summary.hardware.model') eq "ProLiant DL360 Gen9") {
    my $error="";
    my $bios="";
    try {
      my $ilo = get_ilo_address($host->name);
      my $client = REST::Client->new();
      $client->setHost("https://$ilo");
      $client->addHeader("Authorization", "Basic blabla==");
      eval {
        local $SIG{ALRM} = sub { };
        alarm 3;
        #$client->GET("/redfish/v1/Systems/1/Bios/");
        my $bios_current = $client->GET("/redfish/v1/Systems/1/Bios/");
        print Dumper $bios_current->responseCode;
        alarm 0;
      };
      if ( $bios_current->responseCode() ne 200) {
        $bios = "none";
        $error = "Redfish API returned code ".$client->responseCode();
        print Dumper $client->responseCode();
        } else {
        my $json = decode_json($client->responseContent());
        #print Dumper $client->responseContent();

        #$bios = $json->{'Bios'}->{'Settings'}->{'ThermalShutdown'};
        $bios = $json->{'ThermalShutdown'};
        #print Dumper $bios;
        print Dumper $json->{'ThermalShutdown'};
        print "API call is ok\n";
        print  Dumper  $client->setHost("https://$ilo");

      }
    } catch {
      $bios = "none";
      $error=$_;
    };

Upvotes: 1

Views: 177

Answers (1)

JGNI
JGNI

Reputation: 4013

You problem has nothing to do with type.

The first thing every Perl coder should learn is the following two statements should appear at the top of every script.

use strict;
use warnings;

These two statements catch a multitude of errors one of which is the cause of your problem.

If you take a look at your eval block

eval {
    local $SIG{ALRM} = sub { };
    alarm 3;
    #$client->GET("/redfish/v1/Systems/1/Bios/");
    my $bios_current = $client->GET("/redfish/v1/Systems/1/Bios/");
    print Dumper $bios_current->responseCode;
    alarm 0;
};

You will see that the variable $bios_current is introduced with the my modifier this restricts the lifetime of the variable to the current scope, in this case the eval block.

So by the time your if statement is run the variable no longer exists and Perl helpfully creates a new empty one for you, Perl then tries to call responseCode() on the empty variable, this fails and normally would terminate the program, however you are inside a try() block at this point so instead of displaying the error the code jumps to the catch bloc instead.

Upvotes: 3

Related Questions