Reputation: 6285
ALL,
I have a file which contains following string:
VERIFYFAIL usbhd-sdb "There were 1 files with viruses detected. The device has been detached. Infections found: "
And here is my code to get the results:
#!/usr/bin/perl
open( INFILE, "/home/me/scan_result" ) || die "Can't open file";
push( @lines, $_ ) while <INFILE>;
print @lines, "\n";
($result_string) = (split /"/, @lines)[1];
print $result_string, "\n";
close INFILE;
However, while the first print successfully prints the string from the file, the second print prints an empty line.
Basically I'm looking for a string between the quotes. But for some reason I'm failing to get it.
Could someone see my error?
TIA!
Upvotes: 0
Views: 63
Reputation: 510
Method 1 : You can use regex match to get the string between double quotes. Learn about "Pattern Memory" here.
my $file = "/path/to/scan_result";
open (my $infile, "<", $file) or die "Can't open :$!";
while (<$infile>) {
print $1."\n" if ($_ = /\"(.*)\"/);
}
Method 2: Similar to your code, split the string at double quotes and get the value at index 1 from the array after the split.
my $file = "/path/to/scan_result";
open (my $infile, "<", $file) or die "Can't open :$!";
while (<$infile>) {
print [split /\"/, $_]->[1]."\n";
}
And, always use three argument form of open.
Upvotes: 1
Reputation: 2466
That code is treating the input as being multiple lines. To apply an operation across elements of an array, you need to use map
:
my @result_strings = map {(split /"/, $_)[1]} @lines;
print join "\n", @result_strings; print "\n";
Upvotes: 1