0

I have a while loop below:

while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        $error_found +=1;
    }
}

After while loop finished, i will match somethings like "ERROR..." and i wanna store them into an array or list or hash. How can i do this?

2 Answers 2

2

Just push the data into an array.

my @errors;
while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        push @errors, $line;
    }
}

Clean things up a little:

my @errors;
while (my $line = <>)
{
    if ($line =~ /ERROR 0x/)
    {
        push @errors, $line;
    }
}

Or maybe even

my @errors;
while (<>)
{
    if (/ERROR 0x/)
    {
        push @errors, $_;
    }
}

Finally, realize that grep would do great here:

my @errors = grep { /ERROR 0x/ } <>;
Sign up to request clarification or add additional context in comments.

2 Comments

There is a typo in the third example, it sould be $_ instead of $line.
@M42, Thanks to Borodin for fixing it.
0
my @arr;
while (<>)
{
    my $line = $_;
    if ($line =~ m/ERROR 0x/)
    {
        push(@arr,$line) ;
    }
}

print "$_\n" for @arr;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.