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

I have a HoL with data in it (lists of hashrefs, as it happens). But, I want to filter some of the lists that are in the top-level hash keys, leaving others keys intact. I did this, and put the altered keys (the lists) into a new HoL, naively thinking I could assign them back like this:

#This bit works foreach (@{$row_data{groups}}){ push @{$new_row_data{groups}}, $_ if $ +{$_}{whatever}==$something_else; foreach (@{$row_data{fields}}){ push @{$new_row_data{fields}}, $_ if $ +{$_}{whatever}==$something_else; #This bit doesn't at all $row_data{groups}=$new_row_data{groups}; $row_data{fields}=$new_row_data{fields};

There are other hash keys in row_data that I wish to keep. I could just copy them over to %new_row_data one by one, but in the spirit of knowing what's going on, could someone show me the correct way to do it. I wanted to use map originally, but I couldn't quite get that going right either.

____________________
Jeremy
I didn't believe in evil until I dated it.

Replies are listed 'Best First'.
Re: Wrestling with HoL
by jeroenes (Priest) on May 16, 2001 at 14:06 UTC
    Well, references can get very confusing. If you copy a reference, you only copy the pointer. If you want to change the data with a copied pointer, you change the original data. You could peek at perlref, perldsc, perllol and perlreftut.

    Having said this, your code can be cleaned up using grep.

    @$row_data{groups} = grep{ $_->{whatever} == $foo } @$row_data{groups} + ;
    To do groups and fields in one sweep:
    for( qw/groups fields/ ){ my $aref = $row_data{$_}; @$aref = grep{ $_->{whatever} == $foo } @$aref; }
    Which assigns the new arrays belonging to groups, fields with the filtered original arrays.

    Hope this helps,

    Jeroen
    "We are not alone"(FZ)