in reply to Assign (key, value) to a hash w/o clobbering hash

Are you looking for something like:

%hash = (%hash, split /X/ 'fooXbar');

I don't think that's particularly efficient tho' as it rewrites the entire hash every time. I'd probably use your second solution and split to an intermediate array.

--
<http://dave.org.uk>

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

Replies are listed 'Best First'.
Re^2: Assign (key, value) to a hash w/o clobbering hash
by reasonablekeith (Deacon) on Sep 28, 2006 at 10:25 UTC
    To avoid this inefficiency, you could always tie your own hash which didn't clobber the original values, by not implementing CLEAR. So your above line becomes.
    %hash = split /X/, 'fooXbar' # added the missing comma ;)
    depends how far you want to go. Full example as follows...

    (BTW I did try to do this with Tie::StdHash, but couldn't figure it out)

    #!/usr/bin/perl use strict; use Data::Dumper; tie my %hash, 'ExpandingHash'; $hash{'still'} = 'here'; %hash = split /X/, 'fooXbar'; print Dumper(\%hash); # I also added a new clear method, which you could use like this. # tied(%hash)->FORCE_CLEAR; __OUTPUT__ $VAR1 = { 'foo' => 'bar', 'still' => 'here' }; #================================================================== package ExpandingHash; use strict; sub TIEHASH { my %self; bless \%self, shift } sub FETCH { $_[0]->{$_[1]} } sub STORE { $_[0]->{$_[1]} = $_[2] } sub FIRSTKEY { each %{$_[0]} } sub NEXTKEY { each %{$_[0]} } sub CLEAR { } # NOT IMPLEMENTED sub DELETE { delete $_[0]->{$_[1]} } sub EXISTS { exists $_[0]->{$_[1]} } sub FORCE_CLEAR { %{$_[0]} = () }
    ---
    my name's not Keith, and I'm not reasonable.

      That's nasty :)

      It's much simpler using Tie::StdHash as you only need to implement the methods that you want to override.

      package Tie::Hash::ExpandingHash; use strict; use warnings; use Tie::Hash; our @ISA = 'Tie::StdHash'; sub CLEAR { } # NOT IMPLEMENTED sub FORCE_CLEAR { %{$_[0]} = () }
      --
      <http://dave.org.uk>

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

        davorg, I did mention I tried to do it with Tie::StdHash :). It's obviously the way to go if one was to choose this method. However, I still can't get a working example going, even using your example above. For me it gives an error when I try to tie the hash...
        Can't locate object method "TIEHASH" via package ...
        the line being
        tie my %hash, 'ExpandingHash';
        and I also tried
        tie my %hash, 'Tie::Hash::ExpandingHash';

        ---
        my name's not Keith, and I'm not reasonable.