Given the following input:
A| 11 162 60 90 — 141 184
B| 231 322 — 306 305 285 350
For A, I want to check if 141 lies between (11,162) OR (60,90) inclusive.
If yes, print “In A, 141 lies between (11,162)”.
Then, I want to check if 184 lies between (11,162) OR (60,90) inclusive.
Since it doesn’t, nothing needs to be printed.
Similarly, for B, I need to print the numbers that lie between (231, 322).
I wrote the following Perl code but I am not getting the correct output.
#!/usr/bin/perl -w
open LIST, "input.txt";
while($line=<LIST>)
{
@elem=split (/\|/,$line);
@nextone=split("--",$elem[1]);
@nextoneone = split(" ",$nextone[0]);
@nexttwo=split(" ",$nextone[1]);
if ($nexttwo[0] > $nextoneone[0] && $nexttwo[0] < $nextoneone[1])
{
print"$elem[0]\t $nexttwo[0]\t $nextoneone[0]\t $nextoneone[1]\n";
}
elsif ($nexttwo[0] > $nextoneone[2] && $nexttwo[0] < $nextoneone[3])
{
print"$elem[0]\t $nexttwo[0]\t $nextoneone[2]\t $nextoneone[3]\n";
}
elsif ($nexttwo[1] > $nextoneone[0] && $nexttwo[1] < $nextoneone[1])
{
print"$elem[0]\t $nexttwo[1]\t $nextoneone[0] \t$nextoneone[1]\n";
}
elsif ($nexttwo[1] > $nextoneone[2] && $nexttwo[1] < $nextoneone[3])
{
print"$elem[0]\t $nexttwo[1]\t $nextoneone[2] \t$nextoneone[3]\n";
}
}
close (LIST);
exit;
I don’t know how many elements are there in each row. Therefore, I do not know how to implement a loop for comparison.
Any guidance on how to improve the code will be appreciated.
Thank you for your help.
Firstly, I would change a couple of things about your script.
1) use strict – it’ll mean you catch any typos
2) give variables more meaningful names – I’ve changed some that make sense based on what I saw, but I don’t know what your script does, so you may have better ones
3) Output some debug, while you’re developing it, so you can see what it’s doing and why it’s not working
You will need two loops – one to loop over the values in the part of the string to the left of ‘–‘ and one to loop over the conditions on the right side. You want to loop through the values in the outer loop and then each time through that you should loop through ALL the conditions in the inner loop.
Note – I’ve left the debug line in there