Petr Vileta wrote:
> How to Perl compel to create copy of hash?
> I have public hash and in sub{} I want to create local copy without
> reference to original.
>
> Example with not acceptable result:
>
> our $hash;
> $hash->{first} = 1;
> $hash->{second} = 2;
> &mysub;
> print $hash->{second};
>
> sub mysub {
> my $new_hash = $hash; # make reference, not local copy
> print $new_hash->{second};
> $new_hash->{second} = 10;
> print $new_hash->{second};
> }
>
>
>>2
>>10
>>10
use strict;
use warnings;
our $hash;
$hash->{first} = 1;
$hash->{second} = 2;
mysub ();
print $hash->{second}, "\n";
exit;
sub mysub {
my %new_hash = %$hash;
# if you still want a hashref here, add a ref and put the -> back in below :
# my %loc_hash = %$hash; my $new_hash = \%loc_hash;
print $new_hash{second}, "\n";
$new_hash{second} = 10;
print $new_hash{second}, "\n";
}
__END__
>
> Example with success but maybe is possible to write it better:
>
> our $hash;
> $hash->{first} = 1;
> $hash->{second} = 2;
> &mysub;
> print $hash->{second};
>
> sub mysub {
> my $new_hash;
> $new_hash->{$_} = $hash->{$_} foreach (keys %{$hash}); # make local copy
> print $new_hash->{second};
> $new_hash->{second} = 10;
> print $new_hash->{second};
> }
>
> Petr Vileta, Czech republic
> (My server reject all messages from Yahoo and Hotmail. Send me your mail
> from another non-spammer site please.)
>
>
>
>>2
>>10
>>2
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs