1

I can manipulate a single array element and add a reference to the array as a value in a hash. Easy. For example, this achieves the desired result:

# split the line into an array
my @array = split;

# convert the second element from hex to dec
$array[1] = hex($array[1]);

# now add the array to a hash
$hash{$name}{ ++$count{$name} } = \@array;

My question: Is it possible to do the same thing using an anonymous array? I can get close by doing the following:

$hash{$name}{ ++$count{$name} } = [ split ];

However, this doesn't manipulate the second index (convert hex to dec) of the anonymous array. If it can be done, how?

1 Answer 1

4

What you are asking for is this

my $array = [ split ];

$array->[1] = hex($array->[1]);

$hash{$name}{ ++$count{$name} } = $array;

But that may not be what you mean.

Also, rather than using sequential numbered hash keys you would probably be better off using a hash of arrays, like this

my $array = [ split ];

$array->[1] = hex($array->[1]);

push @{ $hash{$name} }, $array;

You need a way to access the array to say what you want to modify, but you could modify it after pushing it onto the hash, like this:

push @{ $hash{$name} }, [split];
$hash{$name}[-1][1] = hex($hash{$name}[-1][1]);

although that's really not very nice. Or you could

push @{ $hash{$name} }, do {
    my @array = [split];
    $array[1] = hex($array[1]);
    \@array;
};

or even

for ([split]) {
    $_->[1] = hex($_->[1]);
    push @{ $hash{$name} }, $_;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank-you Borodin. I guess my question was - can $array also be anonymous? I can see now that it can't be. I will also implement you're HoA suggestion. Cheers.
$array is a reference to an anonymous array; does that help? You could do $hash{$name}{ ++$count{$name} } = map [$_->[0], hex($_->[1]), @$_[2..$#$_]], [split]; but that would be silly
here is another variation on this theme: $hash{$name}{ ++$count{$name} } = (map { $_->[1] = hex($_->[1]); $_ } ([split]))[0];
oh, oops, you are right, the ()[0] is needed around the map (or parens around $hash{$name}{++$count{$name}} to make it a list assignment)
All imran and ysth's options do is store the array reference in $_ instead of an explicit $array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.