Beginner wrote:

On 9 Nov 2007 at 14:59, Rob Dixon wrote:

Beginner wrote:

Is it possible to make a hash slice like so
It's certainly possible, but I'm not sure why you've taken a reference
to your key and value arrays. [EMAIL PROTECTED] is a single scalar value, as is
[EMAIL PROTECTED], so you're creating a single hash element. Perl has had to
stringify the reference to @keys as Perl hash keys must be strings.
The hash value is a reference you your @vals array which contains the
values 1 through 4 as Dumper shows.

I see, scalar used where list expected.

Nope, not this time! But you used a hash slice of one element:

 @[EMAIL PROTECTED] = [EMAIL PROTECTED];

is the same as

 my ($k, $v) = ([EMAIL PROTECTED], [EMAIL PROTECTED]);
 @hash{$k} = $v;

which is ok, but does the same thing as

 $hash{$k} = $v;

How about this:

#!/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @keys = qw(fe fi fo thumb);
my @valone = 1..4;
my @valtwo = 10..14;
my %hash;
@[EMAIL PROTECTED] = [EMAIL PROTECTED],@valtwo];

print Dumper(\%hash);
$VAR1 = {
          'fo' => undef,
          'fi' => undef,
          'fe' => [
                    1,
                    2,
                    3,
                    4,
                    10,
                    11,
                    12,
                    13,
                    14
                  ],
          'thumb' => undef
        };

Alright, that's equivalent to

my @vals = (@valone, @valtwo);
my $v = [EMAIL PROTECTED];

@[EMAIL PROTECTED] = $v;

and because there are four keys in the slice and only one value, the
trailing three get set to undef.

I can't see why you can't create a slice hows values are arrays or why all the values are assigned to the first key.

Not a biggy. I can work around it but I'm interested to know.

Each hash element must have exactly one key and one value, but you've
got an array of four keys and a list of nine values (1, 2, 3, 4, 10,
11, 12, 13, 14). Four keys can't be paired with nine values! What do
you actually want here?

@[EMAIL PROTECTED] = (@valone, @valtwo);

pairs the first four values to the keys in the array and throws away
the remaining five.

Don't forget that a reference is a single scalar value, so both

 [EMAIL PROTECTED]

and

 [EMAIL PROTECTED], @valtwo]

are one scalar.

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to