uprightbassfan78
uprightbassfan78

Reputation: 352

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:

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.

Upvotes: 3

Views: 740

Answers (1)

choroba
choroba

Reputation: 241968

Hashes aren't ordered in 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.

Upvotes: 7

Related Questions