Search code examples
perl

Why is the variable not available?


In the below code block I get this error

Variable "$host" is not available at /comp/xx.pm line 404.

where line 404 is the last line in the code block.

Question

I am guessing that it is the Capture module that is messing up the if (defined $host) { ..., but how can I work around this?

use Capture::Tiny 'capture';

my $host = $::c{slaves}{$id} if (defined $id);

my ($stdout, $stderr, $exit) = capture {
    if (defined $host) {
        print "---delete $snap on host\n";
    } else {
        print "----delete $snap on master\n";
    }
}; # line 404

Update

If I comment line capture and its closing bracket, then it executes the expected print line.


Solution

  • The problem is this line:

    my $host = $::c{slaves}{$id} if (defined $id);
    

    Using my $x = value if condition is not currently supported in Perl. It sort of works, but has weird corner cases. This is one.

    Split the assignment from the declaration of the variable:

    my $host;
    $host = $::c{slaves}{$id} if (defined $id);
    

    You can read some more details in the documentation for the related warning.