Bijan
Bijan

Reputation: 8602

Perl: Reset $1 variable

I have a subroutine that works on the first time it is called but on the second time, if the URL is not valid, it uses the previous value of $1. Is there a simple way to rest the value of $1 or to be equal to a NULL value?

Edit: Here is my code

our %hash;
sub GetOnce{
    $mech->get($_[0]);
    $val = $mech->content;
    $val =~ /value="(.*?)"/;
    if($1 ne "") {$hash{$_[1]} = $1;}
}
GetNonce("http://URL1", "VAR1"); #Valid URL
GetNonce("http://URL2", "VAR2"); #Timesout

I just want to reset the value for Error Handling. I.e. if URL1 is valid but URL2 is invalid or timesout, then $1 will be the same for both of them. If URL1 is invalid/timesout and URL2 is valid, then only the $1 from URL2 is saved. And if they're both valid, then the program stores each of their $1's.

Upvotes: 1

Views: 1100

Answers (2)

Borodin
Borodin

Reputation: 126722

You should test the regex match itself, rather than the value of the captures. It is also best to name the values in @_, and to use a complementary character class instead of a non-greedy match in your regex.

Like this

our %hash;

sub get_once {
    my ($url, $key) = @_;
    $mech->get($url);
    my $content = $mech->content;
    $hash{$key} = $1 if $content =~ /value="([^"]*)"/;
}

Upvotes: 3

Sobrique
Sobrique

Reputation: 53478

I'd suggest not using $1, and instead:

my ( $match ) = ( $val =~ m/value="(.*?)"/ );

Useful feature of pattern matching like this - in a scalar context, it's a 'true/false' but in a list context, it returns a list of matches. Which you can then assign to individual scalars.

So anyway - $match is undef if the match fails, and whatever is in the match if it worked. You should make a point of using defined to test this though, because if the value in $match is 0 or '' it'll evaluate false, despite having worked.

E.g.:

our %hash;
sub GetOnce{
    my ( $url, $key ) = @_; 
    $mech->get($url);
    my ( $match ) = ( $mech -> content =~ m/value="(.*?)"/ ); 
    #may not need to test it -  you could just have an undef value. 
    if ( defined $match ) { $hash{$key} = $match };
}

Upvotes: 6

Related Questions