简体   繁体   English

增加散列Perl中的值

[英]Incrementing values in a hash Perl

I'm trying to increment hash values , but I'm getting confusing output. 我正在尝试增加哈希值,但我的输出混乱。 I'm passing an array of arrays, hashes and scalar values into a function. 我将一个数组,散列和标量值数组传递给函数。

The code below intends to see first of all if it is a hash and if so goes through the values and increments them. 下面的代码打算首先看看它是否是一个哈希值,如果是这样的话,它会通过值并递增它们。

elsif (ref($_) eq "HASH"){

        foreach $s (values %{$_}){
            $s++;
        }
    }

I'm passing in the following hashes: 我正在传递以下哈希:

 { a => 1, b => 2, c => 3  }, { d => 4, e => 5 },

Yet when I print or return $s I get varying output, such as: 然而,当我打印或返回$ s时,我会得到不同的输出,例如:

4 2 3 5 6

or 要么

2 4 3 6 5

or some other random variation. 或其他一些随机变化。 What I want is, obviously, 我想要的是,显然,

2 3 4 5 6

I'm sure it's something very simple, but I'm not very experienced in Perl. 我确信这很简单,但我在Perl方面不是很有经验。

Hashes aren't ordered in Perl. 散列不是在Perl中订购的。 If you want the values sorted, sort them: 如果要对值进行排序,请对它们进行排序:

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $ref = { a => 1, b => 2, c => 3 };

$_++ for values %$ref;
say join ' ', sort values %$ref;        # By values.
say join ' ', @$ref{ sort keys %$ref }; # By keys.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM