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

hi all, can anybody help me in deciphering the following code in perl.
my %br_tsh = (%$tsh, begin_time => $tsh->{break_begin_time}, end_time => $tsh->{break_end_time}, work_day_ind => 'N', );
now my question is that in new hash {br_tsh}, the tsh value are copied or not?? and if {begin_time} and {end_time} keys are already there in the tsh whether this will be updated by the later part of the code??

Replies are listed 'Best First'.
Re: Hash Copy Decipher???
by chromatic (Archbishop) on Apr 25, 2007 at 06:18 UTC

    This code does copy the values of $tsh, but it's a shallow copy. Copies of the values that are references will still point to the same place that the references in $tsh point.

    You're also correct that the three pair declarations after %$tsh will overwrite any values of $tsh with those keys.

      I hesitate to question chromatic on such things, but is the second part of that necessarily true? Since the elements of %$tsh are interpolated into a list, what we have is a list assignment to a hash where the same key may appear more than once, and my impression was that it was undefined which of the two values would be used. OTOH, I looked in perldata just now and the only mention I could find of this topic was:
      A hash can be initialized using a literal list holding pairs of items to be interpreted as a key and a value:
      and no mention of what happens when a key is duplicated.
        I hesitate to question chromatic on such things, but is the second part of that necessarily true?

        Hash keys don't have (easily identifiable) order, but lists certainly do.

        There's no requirement that a tied hash do anything specific when overwriting an existing key, but if Perl suddenly changes the order of operations when processing lists, you'll know it.

Re: Hash Copy Decipher???
by naikonta (Curate) on Apr 25, 2007 at 06:23 UTC
    Hi kunalg,

    The $tsh is dereferenced to populate %br_tsh and it's a form of copying as well. Meaning, further change on %br_tsh, for example, $br_tsh{some_key} = 'newvalue' won't affect $tsh->{some_key} (assuming the key exists).

    If begin_time and end_time exist in $tsh, they are both overridden in %br_tsh due to explicit assignments. Any later update on %br_tsh doesn't affect $tsh.

    HTH,


    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Re: Hash Copy Decipher???
by andye (Curate) on Apr 25, 2007 at 13:31 UTC
    Hiya,

    chromatic and naikonta have already answered this one, but just for the future: you might find the Data::Dumper module useful. It lets you see what's inside a data structure.

    You use it like this:

    use Data::Dumper; print Dumper(\%br_tsh); print Dumper($tsh);

    HTH!

    Best wishes, andye