R
R
ReD2015-11-17 10:59:23
Perl
ReD, 2015-11-17 10:59:23

How to find one line in the text in perl and compare?

There is a task to find a certain place in a text file that
starts with a line, for example "Value", and check the value
after the colon and output the line if it matches the value "A1".
(there is only one such line in the file!)

open(F1, "/text.txt");
my @raw=<F1>; 
chomp (@raw);
foreach $line (@raw)
{    
    $line =~ m/^\bValue\b\s+:\s+([A-Z0-9]+)$/o;
    if ($1 eq A1)
    {
        print "$line \n";
    }
    
}
close(F1);

It turns out for me that, starting from the desired line, the entire rest of the lines from the file falls out, instead of the one required.
How to fix this behavior?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pcdesign, 2015-11-17
@trinitr0

It is necessary to quote
$1 eq "A1"
And so I created a text.txt file with the following content:

uihkjh
dsfkljsdklf 
Value : A1
dfds

use strict;
use warnings;
use utf8;

open( F1, "text.txt" );
my @raw = <F1>;
chomp (@raw);
foreach my $line (@raw) {
    my ($val) = $line =~ m/^\bValue\b\s+:\s+([A-Z0-9]+)$/o;
    next unless $val;
    if ( $val eq "A1"  ) {
        print "$line \n";
    }

}
close(F1);

Changed your code a bit.
Result:
Value : A1

P
Pavel, 2015-11-26
@PavelKuptsov

In my opinion it would be nicer like this:

#!/usr/bin/perl -w

use strict;

open(F1, "<","test.txt") || die $!;
while(<F1>)
{
        chomp;
        /^\bValue\b\s+:\s+([A-Z0-9]+)$/g;
next unless $1;
    if ($1 eq "A1")
    {
        print "$_\n" and exit 0;
    }

}
close(F1);

This, firstly, does not require a complete reading of the file (after we have found the value, we exit the program), and secondly, less memory consumption (you first read the file into an array - which is not necessary, line-by-line reading through while () is better)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question