Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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);
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question