finding records matching particular keyword from an array in perl
I am having a problem in the program code as I have changed my file into an array but not sure whether it has been changed or not. So please check the code given below also it is showing an error of use of uninitialized @data in last line.
Now after this, my biggest problem is that I want to collect only those elements within an array which have a specific keyword in between them. For example, each array's element starts from where women
ends and children
begin开发者_Go百科s. These words are common in all the other elements but information in between them are different and I want only those elements which has a keyword 'factor man' somewhere in between so I want to extract not all but only those elements which are having keyword 'factor man'.
As you can see that my file is having all the initial words common in all the elements but after that the information is different but each element has a start from women
and ends at children
. please anyone could guide me regarding this.Thanks in advance.
Input file
women bds1
origin USA
accession not known
factor xyz
work abc
children
women sds2
origin ENG
accession known
factor man
work wwe
children
women cfc4
origin UK
factor xxx
work efg
children
women gtg6
origin UAE
factor man
work qqq
children
script
#!/usr/bin/env perl
use strict;
use warnings;
my $ifh;
my $line = '';
my @data;
my $ifn = "fac.txt";
open ($ifh, "<$ifn") || die "can't open $ifn";
my $a = "women ";
my $b = "children ";
my $_ = " ";
while ($line = <$ifh>)
{
chomp
if ($line =~ m/$a/g); {
$line = $_;
push @data, $line;
while ($line = <$ifh>)
{
$line .= $_;
push @data, $line;
last if
($line =~ m/$b/g);
}
}
push @data, $line; }
print @data;
output
women sds2
origin ENG
accession known
factor man
work wwe
children
women gtg6
origin UAE
factor man
work qqq
children
#!/usr/bin/perl
use strict;
use warnings;
my @AoH;#Array of hashes
my $ifn = 'fac.txt';
open my $fh, '<', $ifn or die "Failed to open $ifn: $!";
my $i = 0;
while(<$fh>){
chomp;
my @flds = split;
$AoH[$i]{$flds[0]}{content} = $flds[1];
$AoH[$i]{$flds[0]}{seqnum} = $.;
$i++ if $flds[0] eq 'children';
}
foreach my $href (@AoH){
if (${$href}{factor}{content} eq 'man'){
foreach my $k (sort {${$href}{$a}{seqnum}
<=> ${$href}{$b}{seqnum}} keys %$href){
my $v;
if (defined ${$href}{$k}{content}){
$v = ${$href}{$k}{content};
}
else{
$v = ' ';#Space if undefined
}
print "$k $v\n";
}
}
}
精彩评论