Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl use strict; use warnings; my $names; my @name; while(<DATA>){ if(/{(.*)}/){ my @names_hash = qw{NAME AGE}; $names = $1; push (@name, $names); next if $names !(exists(@names_hash)); print $names; } } print @name; __DATA__ {NAME} {AGE} {SEX} {ADDRESS} {ADDRESS}
How to print the values only when $names only when $names doesnot exists in @names_hash

Replies are listed 'Best First'.
Re: print the values
by grizzley (Chaplain) on Nov 05, 2009 at 08:52 UTC

    Why an array has the name names_hash? You are correct you want hash there, so define hash, not array:

    #!/usr/bin/perl use strict; use warnings; my $names; my @name; while(<DATA>) { if(/{(.*)}/) { $names = $1; my %names_hash = qw{NAME 1 AGE 1}; push @name, $names; next if ! exists $names_hash{$names}; print $names; } } print @name; __DATA__ {NAME} {AGE} {SEX} {ADDRESS} {ADDRESS}
      Thanks but the $names prints the names which exists in the %names_hash.
      How to print the values which doesnot exists in the %names_hash

        Don't push them into @names if they already exist in %names_hash; add a conditional to the line with the push.

        Change skip condition to the opposite, from

        next if ! exists $names_hash{$names};

        to

        next if exists $names_hash{$names};
Re: print the values
by Marshall (Canon) on Nov 05, 2009 at 17:34 UTC
    First, I would say that your indenting style is quite frankly horrible. I really like what grizzley did and I commend it! Your code also doesn't "run".

    If you have a choice of print instead of push and print later, print it now!

    #!/usr/bin/perl -w use strict; my %names = qw (NAME 1 AGE 1); while(<DATA>) { s/[{}\n]//g; #this substitute gets rid of {} and also #does the job of chomp; print "$_\n" if !exists($names{$_}); } # Prints: # SEX # ADDRESS # ADDRESS __DATA__ {NAME} {AGE} {SEX} {ADDRESS} {ADDRESS}