Re: Help with using sub to update hash

On Thu, 2007-03-08 at 02:58 +0000, Mike Martin wrote:
I have the following code

Ouch, that code is really hard to read.  Please tell me pasting the code
into google mail ate all your indentation and you didn't actually format
it that way on purpose :-)

my %titles;
my %dvd_titles;

Ok, so these are hashes that exist in the scope of the caller.

$dvd_act_btn->signal_connect('clicked'=>sub{$count++ &&

And when you call dvd_setup you pass it a reference to each hash - good.

sub dvd_setup {
my ($vbox2,$count,$sel_opts_vbox,$titles,$dvd_titles)= _;

Now $titles is a reference to %titles and $dvd_titles is a reference to
%dvd_titles - also good.

But this is where you go off the rails ...

my %titles=%{$titles};
my %dvd_titles=%{$dvd_titles};

Now you've created a new hash called %titles which is scoped to within
the subroutine and you've *COPIED* the contents of the hash referenced
by $titles into the new one.  Ditto for %dvd_titles.

You mentioned that updates to these hashes in the subroutine have no
effect but there are two problems

 1. your sample code never does an update
 2. if it did, it's probably updating the copy rather than the original

Probably what you want to do is skip the my %titles=%{$titles}; bit.

Then, to update, instead of doing this:

  $titles{$key} = 'value';

do this:

  $titles->{$key} = 'value';

The arrow (->) means operate on the hash referred to by $titles.

It just seems like you're not clear on what a hashref is and the syntax
for using one.  The standard Perl documentation includes a tutorial on

Since this is not Gtk-specific, can I suggest taking it to if you need more help.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]