in reply to Strange bug with map

Thank you both for your answers. I didn't realize that $_ was not local, that explains it indeed.

But now I have a follow up question: I don't understand why the values in the hash are affected? In my mind I assumed that $_ receives a copy of the ref to the object, so I didn't expect that when $_ is set to undef the values in the hash become undefined as well. Here is an example of what I mean:

my @docsObservs; foreach my $docP (values %{$self->{docs}}) { push(@docsObservs, $docP->getObservations()); die "loop variable is undef after call to getObservations()" if (!de +fined($docP)); $docP = undef; } map { die "bug after!" if (!defined($_)); } values %{$self->{docs}};
It turns out that this version dies with the "bug after" error. Is this somehow related to how the values function works? It looks as if $docP is some kind of "hard link" to the object, and not a simple copy of the ref.

Replies are listed 'Best First'.
Re^2: Strange bug with map
by choroba (Cardinal) on Feb 11, 2016 at 16:08 UTC
    This behaviour is documented in values:

    > Note that the values are not copied, which means modifying them will modify the contents of the hash.

    It's convenient, you can do things like

    $_ = lc for values %hash;

    Note that keys don't work this way.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Sorry I didn't see your answer before finding it by myself. ok now I see the point, thank you

Re^2: Strange bug with map
by erwan (Sexton) on Feb 11, 2016 at 16:17 UTC

    ok sorry, I should have read the documentation before asking:

    "Note that the values are not copied, which means modifying them will modify the contents of the hash" http://perldoc.perl.org/functions/values.html

    I find this a bit counter-intuitive actually, but that answers my question clearly.