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

Dear Monks,

Why does the code below not work ?
#! /usr/bin/perl $a = { aa => 'b', bb => 'd', le1 => 'sad', le2 => 'ss' } ; ($c->{$_}) = grep { ! /le/, $a->{$_} } keys %$a ; foreach (keys %$c) { print "key=$_ et val=$c->{$_}\n" ; }
update: So I only would like to ignore the 'le' keys!!

Thanks a lot
Luca

Replies are listed 'Best First'.
Re: create hash using grep
by borisz (Canon) on Feb 21, 2006 at 12:29 UTC
    If you want grep and $c must be a reference here is one way:
    #! /usr/bin/perl $a = { aa => 'b', bb => 'd', le1 => 'sad', le2 => 'ss' } ; my @keys = grep { ! /le/ } keys %$a ; @$c{@keys} = @$a{@keys}; foreach (keys %$c) { print "key=$_ et val=$c->{$_}\n" ; }
    Boris
      yes!! but what is the @$c{@keys} ?
      Where can I read about this type of variable usage... ?

      Luca
Re: create hash using grep
by davorg (Chancellor) on Feb 21, 2006 at 12:31 UTC
    Why does the code below not work ?

    For a number of reasons. But mainly because grep returns the value of $_ and because your hash assignment is completely wrong?

    Why not try turning on use strict and use warnings and see what it says.

    You probably want something like this (untested):

    my %a = %$a; my @keys = grep { ! /le/ } keys %$a; my %c; @c{@keys} = @a{@keys}; my $c = \%c;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: create hash using grep
by mickeyn (Priest) on Feb 21, 2006 at 13:04 UTC
    Hi Luca,

    You should consider the fact that 'grep' creates a temporary data structure and that Perl's garbage collection probably won't release it back to the OS (from my experience).

    Please consider a simpler way to do what you ask without consuming exessive memory -

    foreach (keys %$a){ !/le/ and $c->{$_} = $a->{$_}; }
    Note that you can use the same loop for adding more restrictions or perform more actions if you need, which may save you run-time in some cases.

    Enjoy,
    Mickey

      You're right, this looks very good, I tried to use grep because I don't really understand it :)

      Thnx
      Luca