vkk05
vkk05

Reputation: 3222

Perl Use of uninitialized value in regexp compilation at warning

I have pasted small snippet of code below:

#!/usr/bin/perl

use strict;
use warnings;
use autodie;

my $start_data;
my $name = "Data_abc";

while(<DATA>){
    my $line = $_;
    if ($line =~ /^Start:\s+/){
        my ($st, $data) = split(/\s+/,$line); 
        $start_data = $data; 
    }

    for( $name ){
        /^$start_data/ and do { next; }
    }

    print "END of execution\n";
}
print $start_data;

__DATA__
===============================
2020-05-20            Name
===============================
Start:              Data_abc
Load:               Load_data

Script is working as expected but it throws up warning -

Use of uninitialized value $start_data in regexp compilation at storage_problem.pl line 18,

Since I have already declared $start_data at the beginning, why this warning it shows?

Upvotes: 2

Views: 1532

Answers (3)

Polar Bear
Polar Bear

Reputation: 6798

The code provided by OP declares $start_data but does not initialize it.

On read of first line this $start_data checked in /^$start_data/ regular expression which is equivalent to /undef/ what causes following message

Use of uninitialized value $start_data in regexp compilation at storage_problem.pl line 18,

Perhaps the code should be written us following

use strict;
use warnings;
use feature 'say';

use autodie;

my $start_data;
my $name = "Data_abc";

while(<DATA>){
    next unless /$name/;
    $start_data = $1 if /^Start:\s+(\w+)/;
}

say 'END of execution';
say "Start: $start_data" if defined $start_data;

__DATA__
===============================
2020-05-20            Name
===============================
Start:              Data_abc
Load:               Load_data

Upvotes: 3

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

Because there is no guarantee that that if block is going to execute.

You can either ask if the variable is set before to read it, or just initialize to whatever value makes sense for your use case.

Upvotes: 1

toolic
toolic

Reputation: 62037

$start_data was declared, but you did not assign it a value before you tried to read it in the regex. Therefore, it is undefined.

When I run your code, I get 3 warning messages, corresponding to your 1st 3 lines of DATA. Those 3 lines do not match your regex (they don't start with Start:).

Since you did not initialize $start_data with a value, you get the uninitialized warning.

Once the 4th line is read, you stop getting the warnings because $start_data is assigned a value (Data_abc).

Upvotes: 4

Related Questions