SPUG: assigning to slice of anon hash?

Doug Beaver doug at beaver.net
Wed Jun 27 15:27:46 CDT 2001


On Wed, Jun 27, 2001 at 12:12:53PM -0700, El JoPe Magnifico wrote:
> Quick (hopefully) perl syntax question that I ran into last night.
> You can assign to a slice of a hash with the following:
> 
>   @hash{ @fields } = @values;
> 
> However, I can't figure out how to do the same with a hash ref.
> The following gives a runtime error, "Can't coerce array into hash",
> since the @{$ref} construct is generally how you deref an array ref:
> 
>   @{ $hash_ref }->{ @fields } = @values;
> 
> And the following (which wouldn't be syntactically consistent,
> but I tried just in case) doesn't do the trick either:
> 
>   %{ $hash_ref }->{ @fields } = @values;

require 'dumpvar.pl';
@fields = 'a'..'e';
@values = 1..5;

@hash{@fields} = @values;
dumpValue(\%hash); print "\n";

$h = {};
@$h{@fields} = @values;
dumpValue($h); print "\n";

$h = {};
@{ $h }{@fields} = @values;
dumpValue($h); print "\n";

You've already dereferenced the ref by sticking the @ in front of it, so
you don't need the ->...  Tested on 5.6.0.

Doug

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list