LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl help with - if exists (https://www.linuxquestions.org/questions/programming-9/perl-help-with-if-exists-520816/)

kshkid 01-19-2007 04:26 AM

perl help with - if exists
 
Hi All,

I would like to know how to have
if else block
if am using
if exists to check whether an entity is available in hash

Code:

#! /opt/third-party/bin/perl
                                                                               
my(%fileHash);
                                                                               
open(FILE,"< $ARGV[0]") || die "Unable to open file $ARGV[0] <$!> \n";
                                                                               
while( chomp($_ = <FILE>) ) {
  $fileHash{$_}++;
}
                                                                               
close(FILE);
                                                                               
open(FILE,"< $ARGV[1]") || die "Unable to open file $ARGv[1] <$!> \n";
                                                                               
while(chomp($_ = <FILE>) ) {
  print "$_\n" if exists $fileHash{$_};
  ### How to have else condition to the above 'if exists' ###
}
                                                                               
close(FILE);
exit 0

Thanks in Advance :)

druuna 01-19-2007 05:00 AM

Hi,

Instead of saying: print "$_\n" if exists $fileHash{$_};

You can also say:

if (exists $fileHash{$_}) { print "Yep, it exists!\n"; }

Which makes adding an else part easy:

Code:

if (exists $fileHash{$_}) {
  print "Yep, it exists!\n";
}
else {
  print "Nope, it doesn't exists\n";
}

Hope this helps.

kshkid 01-19-2007 05:43 AM

Yes Definitely! :)

Thanks a lot for the help!

I should have the habit of structured learning. :)


All times are GMT -5. The time now is 06:47 AM.