Your second line has more than one space between the number group and the letter, so you probably want \s+
both times rather than \s
the second time.
You won't necessarily know how many items you have in the @value
array at the end, so you might want to put the printing into a for
loop rather than assume you have a fifth item. (Maybe you know you want the first and fifth, however?) Follow-up: based on your edit, you have more than two entries after all. The version that I give below, using split
and \s+
captures the number and letter for all the lines. I'll adjust the print part of the script to show you what I mean.
A few other things:
- You should always enable warnings.
- There's no reason to read the whole file into an array and then process through it line by line. Skip the
@body
array and just do what you need to in the while
loop.
- Use the more modern form of
open
with lexical filehandles and three arguments.
split
seems more straightforward here to me, rather than a regular expression with captures. Since you want to capture two specific parts of the line, you can use split
with an array slice to grab those two items and feed them to join
.
@value
is not an especially helpful variable name, but I think you should at least make it plural. It's a good habit to get into, I think, insofar as the array stores your plural records. (That's not a hard and fast rule, but it bugged me here. This point is pretty minor.)
Here's how all this might look:
#!/usr/bin/env perl
use warnings;
use strict;
my @values;
# open my $filehandle, '<', '/usr/test'
# or die "Can't open /usr/test: $!";
while (my $line = <DATA>) {
chomp $line;
push @values, join('', (split /\s+/, $line)[1..2]);
}
for my $record (@values) {
print $record, "\n";
}
__DATA__
1389 E not
188 S yes
24 D yes
456 K not
2 Q yes