How to extract many lines from a file and separate the same
I have the code as follows:
#!/usr/local/bin/perl
use warnings;
use strict;
my $inputfile = "file1.txt";
open FH,$inputfile;
my @results = <FH>;
close FH;
print "\n---------type n--------------\n" ;
foreach my $line (@results) {
if ($line =~ m/(^Mgn\d\.qna.*)/i)
{
print "$1\n";
} 开发者_JAVA技巧
}
print "\n---------type p--------------\n" ;
foreach my $line (@results) {
if ($line =~ m/(^Mgp\d\.qpa.*)/i)
print "$1\n";
}
}
The following code prints lines starting from Mg1.qna ..... now I've to add an alphabet at the end of each line as a, b, c, ...... can someone enlighten me on this
I did a couple of changes:
- I added a
chomp
to remove the\n
character at the end of each line. It might not make any difference, but it could. Remember when you read in input, it might contain the\n
character on the end. - I added a
$code++;
.
One of the nice things about Perl is that it's pretty smart about auto-incrementing things. You try to auto-increment something with letters in it, and Perl assumes you want to update it alphabetically.
Thus, I simply set $n_code
and $p_code
to "a", and let Perl handle the incrementing.
You weren't very clear what you were looking for, so I hope this is what you meant.
Next time, include some sample input and output. A half dozen lines of each would have been very helpful.
#!/usr/local/bin/perl
use warnings;
use strict;
my $inputfile = "file1.txt";
open FH,$inputfile;
my @results = <FH>;
close FH;
print "\n---------type n--------------\n" ;
my $n_code = "$a";
foreach my $line (@results) {
chomp $line; # Remove possible NL
if ($line =~ m/(^Mgn\d\.qna.*)/i)
{
print "$1 $n_code\n";
$n_code++; #Increment code to next alphabet character
}
}
print "\n---------type p--------------\n" ;
my $p_code = a;
foreach my $line (@results) {
chomp $line; #Remove possible NL
if ($line =~ m/(^Mgp\d\.qpa.*)/i)
print "$1 $p_code\n";
$p_code++; #Increment code to next letter of alphabet
}
}
like this??
my @type_p;
my $l='a'; # ++ op will increment it
print "\n---------type n--------------\n" ;
foreach my $line (@results) {
if ($line =~ m/(^Mgn\d\.qna.*)/i) {
print $1.($l++)."\n";
} elsif ($line =~ m/(^Mgp\d\.qpa.*)/i) { #avoid the 2nd foreach loop
push @type_p,$1;
}
}
print "\n---------type p--------------\n" ;
#$l='a'; #reset counter
print $_.($l++)."\n" for (@type_p);
精彩评论