Perl Question Grep and exit status

Im being forced to write in perl. I prefer KSH or Expect, so I suppose its time to become more fluent with perl.

I have the following problem. I want to loop through Filea and check that each line in Filea is resident in Fileb.

Filea contents
two
four
six
eight
houseboat

Fileb contents
one
two
three
four
five
six
seven
eight
nine
ten

In ksh

 cat filea | while read x; 
do 
grep $x fileb >/dev/null 
echo $?; 
if [ "$?" = "1" ] 
then
echo "Error, $x not resident"
fi
done

Heres what I got so far in Perl. Im trying to resist the urge to use exec() and system(). Where you see the pseudo code is where Im stuck.

#!usr/bin/perl
use strict; 
use warnings;
use Data::Dumper;
use vars qw ( @FA $lineinfilea );
open (iFILEA, "<filea") or die;
@FA = <iFILEA>;
close iFILEA;
#
open (iFILEB, "<fileb") or die;;
@FB = <iFILEB>;
close iFILEB;
#
foreach $lineinfilea  (@FA) {
 chomp $lineinfilea;
 print $lineinfilea, "\n";
   #PSEUDO code 
   #grep $lineinfilea @FB
   #  if the exit status of grep $linefilea @FB is 1 
   #   then  
   #   print $lineinfilea, "is not resident.\n;
   #
}

Thanks very much for the help !

PS That's why I like KSH .. a lot less typing :slight_smile: ..

This is listed in perlfaq.

have a look How can I tell whether a certain element is contained in a list or array?

1 Like

Thanks you.

---------- Post updated 05-14-13 at 10:10 AM ---------- Previous update was 05-13-13 at 02:40 PM ----------

Ok this was working yesterday .. not sure why its not working today ...

#! /usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $lineinfilea;
my @FA;
my @FB;
open (iFILEA, "<filea") or die;
@FA = <iFILEA>;
close iFILEA;
#
open (iFILEB, "<fileb") or die;
@FB = <iFILEB>;
close iFILEB;
#
foreach $lineinfilea  (@FA) {
 chomp $lineinfilea;
 print $lineinfilea, "\n";
 if ( $lineinfilea ~~ @FB ) {
   print "The array contains $lineinfilea\n";
 } else {
  print "The array doesnt contain $lineinfilea\n";
 }

Todays output ...

two
The array doesnt contain two
four
The array doesnt contain four
six
The array doesnt contain six
eight
The array doesnt contain eight
houseboat
The array doesnt contain houseboat

Test files are as originally posted.

Any suggestions ?

Efficient and easy with awk:

awk 'NR==FNR {a[$1]; next} !($1 in a) {printf "Error, %s not resident\n",$1}' fileb filea

---------- Post updated at 10:57 AM ---------- Previous update was at 10:03 AM ----------

After some googling and trying, I found how to do it in perl

#!/usr/bin/perl -w
my %FB;
open (Fb, "<fileb") or die;
while (<Fb>) {
  chomp;
  $FB{$_}="";
}
close Fb;
open (Fa, "<filea") or die;
while (<Fa>) {
 chomp;
 print "Error, $_ not resident\n" unless exists $FB{$_};
}
close Fa;

What are the versions of Perl you used yesterday and today?