Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
999 views
in Technique[技术] by (71.8m points)

perl - How to do sum of hash reference slice?

I'm trying to get a sum of a hash reference slice, but I am failing

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use feature 'say';
use autodie ':all';
use List::Util 'sum';

my %h = (
    'a' => 1,
    'b' => 2,
    'c' => 3
);

my @letters = ('a','b');
say sum(@h{@letters}); # 1+2 = 3, which is correct
my $h = \%h; # create a reference
#say sum(@{ $h->{ @letters } }); # says "uninitialized value"
#say sum(@{ $h }->{@letters}); # not an array reference
say sum(@h->{@letters}); # @h requires explicit package name

I can get the sum of the hash slice, but not the sum of a slice of a hash reference.

All three methods that I've tried have failed to get the sum, and I've indicated the errors in the comments.

How can I get the sum of a hash reference slice?

question from:https://stackoverflow.com/questions/65837342/how-to-do-sum-of-hash-reference-slice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Dereference the $h with the @ sigil but follow it with a curly brace:

say sum(@{ $h }{ @letters });

If the thing inside the @{...} is a simple scalar, the curly braces are optional. So, you can shorten it to

say sum(@$h{ @letters });

The third possible syntax is the Postfix Reference Slicing (needs 5.20+):

say sum($h->@{ @letters });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...