- Always use use strict;! It finds an error immediately in this case.
- s{ \A (\S+) \s+ (?= \d ) }{}xms only has one capture, so $2 will always be undef
- No line in File2 has a space followed by a digit, so s{ \A (\S+) \s+ (?= \d ) }{}xms will never match.
#!/usr/bin/perl
use strict;
use warnings;
my $qfn1 = "File1.txt";
my $qfn2 = "File2.txt";
my %positions;
{
open(my $fh, '<', $qfn1)
or die("Cannot open file \"$qfn1\": $!\n");
while (<$fh>) {
my ($key, $pos) = split /\s+/;
$positions{$key} = $pos;
}
}
{
open(my $fh, '<', $qfn2)
or die("Cannot open file \"$qfn2\": $!\n");
for (;;) {
defined( my $key = <$fh> )
or last;
defined( my $text = <$fh> )
or last;
chomp($key);
chomp($text);
defined( my $pos = $positions{$key} )
or next;
$pos = $pos - 1 - 3;
$pos >= 0
or next;
my ($str) = $text =~ /^.{0,$pos}FAN(.{3})/
or next;
print("$key: $str\n");
}
}
12345: ABC
67890: JAK