Dinesh Sharma
Dinesh Sharma

Reputation: 1

perl variable not storing data outside block

I have written below mention code to read a file and and storing data to array @s_arr.

But when I am trying to print that @s_arr array outside the block it shows nothing.

use Data::Dumper;

my @s_arr;
my @err;
my %sort_h_1;

$fname = '/qv/Error.log';

open( IN, "<$fname" );

foreach $line ( <IN> ) {

    if ( $line =~ /CODE\+(\w{3})(\d{5})/ ) {
        $a = "$1$2";
        push @err, $a;
    }
}

close IN;

$prev  = "";
$count = 0;

my %hash;

foreach ( sort @err ) {

    if ( $prev ne $_ ) {

        if ( $count ) {
            $hash{$prev} = $count;
        }

        $prev  = $_;
        $count = 0;
    }

    $count++;
}

print Dumper \%hash;

printf( "%s:%d\n", $prev, $count ) if $count;

$hash{$prev} = $count;
my $c = 0;

print "Today Error Count\n";

foreach my $name ( sort { $hash{$b} <=> $hash{$a} } keys %hash ) {

    #printf "%-8s %s\n", $name, $hash{$name};
    #my %sort_h ;

    push @s_arr, $name;
    push @s_arr, $hash{$name};

    #$sort_h{$name} = $hash{$name} ;
    #print Dumper \%sort_h ;
    #print Dumper \@s_arr ;

    $c++;

    if ( $c eq 30 ) {
        exit;
    }
}

print Dumper \@s_arr;    #  It's showing nothing

Upvotes: 0

Views: 68

Answers (1)

simbabque
simbabque

Reputation: 54323

You are calling exit inside of your foreach loop. That makes the program stop, and the print Dumper @s_arr is never reached.

To break out of a loop you need to use last.

foreach my $name ( sort ...  ) {

    # ...

    $c++;

    last if $c == 30; # break out of the loop when $c reaches 30

}

I used the postfix variant of if here because that makes it way easier to read. Also note that as zdim pointed out above, you should use the numerical equality check == when checking for numbers. eq is for strings.

Upvotes: 4

Related Questions