On Sun, Aug 19, 2012 at 10:48 PM, timothy adigun <2teezp...@gmail.com>wrote:

> Hi,
>
> Please, Check my comments below.
>
> On 8/19/12, jet speed <speedj...@googlemail.com> wrote:
> > Hi All,
> >
> > Is there a way to find  matching array elements from hash.
> >
> > ex:
> >
> > @names = ( abc. def. ghi, jky; );
>
>   The above should be @names=("abc","def","ghi","jky");
>     OR
>    @names=qw(abc def ghi jky); OR other variant but what you have written.
> >
> > %stud  = (
> > " abc" =>" 34",
> > "nba" =>"99",
> > "def" =>"24",
> > "ghi"=> "33");
>
>   You really don't on most cases what to quote the keys in the hash,
> since you are using the FAT arrow, which already does that, except for
> some few cases.
>
>   So, you have this:
>  my %stud = (
>     abc => "34",
>     nba => "99",
>     def => "24",
>     ghi => "33"
> );
>
> > How can i go throught each elements of has %stud and print the matching
> > array value in this case
> >
>   You can use smart-match "~~" with a foreach loop, like so:
>
> use warnings;
> use strict;
>
> my @names = qw(abc def ghi jky);
>
> my %stud = (
>     abc => "34",
>     nba => "99",
>     def => "24",
>     ghi => "33",
> );
>
> foreach my $match_value ( sort keys %stud ) {
>     print $match_value, "=", $stud{$match_value},
>           $/ if $match_value ~~ @names;
> }
> __END__
>
> abc=34
> def=24
> ghi=33
>
> Warning: Though it might not be so effective if you have to loop
> through a long data list. You might take a look at the the function
> first in module List::Util.
>
> > abc =34
> > def=24
> >
>  ghi=33 will also match.
>
> Hope this helps.
> > Thanks
> > Sj
> >
>
>
Hi Tim,

Thanks, i tried to run the code, but get the error as below. Any thing i am
missing line 17.

 syntax error at ./match2.pl line 17, near "$match_value ~"
Execution of ./match2.pl aborted due to compilation errors.

 more match2.pl
#!/usr/bin/perl

use warnings;
use strict;

my @names = qw(abc def ghi jky);

my %stud = (
    abc => "34",
    nba => "99",
    def => "24",
    ghi => "33",
);

foreach my $match_value ( sort keys %stud ) {
    print $match_value, "=", $stud{$match_value},
          $/ if $match_value ~~ @names;
}


> --
> Tim
>

Reply via email to