Johnson, Reginald (GTI) wrote:
I am trying to grep an array return the lines that match. From my
reading I see that grep returns the number of times an expression was
true not the actual expression. My question is how would I get the
actual expression.
I tested my code with a small input file of 2 records. The first one is
in the @mhsarray the second one is not.
I am trying to get my output file to have "CISCSTT6....line from
@mhsarray that it matched".
$ cat mhs.pl
#!/usr/bin/perl
use warnings;
use strict;
$file="/adsm/nodes";
$mhs="/adsm/mhs_alloc";
$file_out="/adsm/in_mhs";
my $file = '/adsm/nodes';
my $mhs = '/adsm/mhs_alloc';
my $file_out = '/adsm/in_mhs';
open (INFILE, "<", "$file") or
die "$file could not be opened: $!";
open (MHSFILE, "<", "$mhs") or
die "$mhs could not be opened: $!";
open (OUTFILE, ">", "$file_out") or
die "$file_out could not be opened: $!";
perldoc -q quoting
while (<MHSFILE>) {
chomp($_);
push (@mhsArray, $_);
}
Or simply:
chomp( my @mhsArray = <MHSFILE> );
foreach $line (<INFILE>) {
while ( my $line = <INFILE> ) {
chomp($line);
print "this is line $line\n";
@inmhs = grep(/$line/,@mhsArray);
$line may contain regexp meta-characters so you should quotemeta() it:
my @inmhs = grep /\Q$line/, @mhsArray;
Or did you really want to check for equality:
my @inmhs = grep $_ eq $line, @mhsArray;
If you just want the number of times that $line matches @mhsArray then
use a scalar:
my $inmhs_count = grep /\Q$line/, @mhsArray;
print "size of inmhs array is $#inmhs\n";
$#inmhs is *not* the size of @inmhs, $#inmhs is the index of the last
element of @inmhs. @inmhs in scalar context is the size of @inmhs.
print "size of inmhs array is ", scalar @inmhs, "\n";
if ($#inmhs > -1) {
Just use @inmhs in scalar context:
if ( @inmhs > 0 ) {
Or simply:
if ( @inmhs ) {
print (OUTFILE "$line\n"); # would like to be $line...line from
@mhsArray
# print "$_\n";
}
} #end foreach
close(INFILE);
close(MHSFILE);
close(OUTFILE);
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/