Given the files:
A. hash.pl:
%h1 = (
A=>['4631 4576','6646 6646',],
B=>['3539 4576',],
);
B. input.txt
4576 4631 4
4576 3539 4
I have to write a Perl code that finds the values (4631 4576) in input.txt. (The order is not important.) Here, ‘4631 4576’ appears as 4576 4631 in input.txt.
I wrote the following code but there seems to be some problem:
#!/usr/bin/perl -w
open (FH, "input.txt") or die "can't open file: &! \n";
require "hash.pl";
foreach $amp (<FH>)
{
if ($amp=~/(\d+)\t(\d+)\t(\d+)/)
{
foreach $keys (keys %h1)
{
@tmparray= @{$h1{$keys}};
foreach $tmp1 (@tmparray)
{
if ($tmp1 =~ m/($1 $2|$2 $1)/ )
{
print "$keys", "$3\n";
}
}
}
}
}
close (FH);
exit;
What is wrong with this code?
This solution uses
doin preference torequireas the latter is intended for inluding library source files and returns a useless scalar value in this context.dosimply returns the value of the last statement executed and so can be used to initialise a local variable.Rather than using a regex, this program just calls
splitto collect the non-whitespace fields in the file. It then checks that there were three and that they were all numeric.Putting the result of the
splitinto an array avoids the problem that the captured regex fields were being lost.The regular expression
$reis built, allowing the first two fields to appear in either order, and thengrepis called on each hash element to verify whether any of the values in the hash value arrays match this file entry.The output seems minimal, but it contains the same information as the original code displayed.
output