Arrays · Hashes

values#

List every value of a hash (or every element of an array).

values is the value-side companion to keys. Given a hash, it returns all the values; given an array, it returns all the elements. The elements come back as aliases into the underlying container, so assigning to them from a loop modifies the container in place. As a side effect, calling values resets the iterator that each, keys, and values share for that hash or array.

Synopsis#

my @v = values %hash;
my @v = values @array;
my $n = scalar values %hash;    # number of values
for (values %hash) { $_ *= 2 }  # mutate in place via aliasing

What you get back#

In list context: the full list of values from a hash, or the full list of elements from an array. Array entries come back in index order (lowest index first). Hash entries come back in an implementation-defined, per-hash random order — see Edge cases.

In scalar context: the number of entries, identical to scalar keys %h for hashes and scalar @a for arrays. values in void context does nothing observable except reset the iterator — that is the idiomatic way to force-reset an iterator mid-traversal:

values %h;                       # void context: iterator reset only

The returned list is not a copy. Each element is an alias to the live value in the container. Aliasing is documented behaviour and is the basis for the in-place mutation idiom under Examples.

Global state it touches#

values resets the per-container iterator state that each reads and advances. Any while (my ($k, $v) = each %h) { ... } loop in progress on the same hash will restart from the beginning the next time each is called. keys has the same effect. The iterator is a property of the container, not of any particular call site — so a caller in one sub can disturb an each loop running in another sub if they operate on the same hash.

Examples#

Iterate a hash in key-sorted order, which values alone does not give you:

my %score = (alice => 90, bob => 75, carol => 82);
for my $k (sort keys %score) {
    print "$k: $score{$k}\n";
}

Sum every value of a hash:

use List::Util qw(sum0);
my %count = (apples => 3, pears => 5, plums => 2);
my $total = sum0 values %count;     # 10

Mutate every value in place through the alias:

my %prices = (bread => 3.00, milk => 2.50, eggs => 4.20);
$_ *= 1.10 for values %prices;      # apply 10% price rise
# %prices is now (bread => 3.30, milk => 2.75, eggs => 4.62)

The same idiom works on an array, though for arrays a plain @array loop is more conventional:

my @nums = (1, 2, 3, 4);
$_ **= 2 for values @nums;          # @nums is now (1, 4, 9, 16)

Force-reset an in-progress each iterator without consuming its output:

while (my ($k, $v) = each %h) {
    last if $v > $threshold;
}
values %h;                          # void context: drop iterator state
# next each %h starts from the beginning

Count entries without building the list — scalar context never materialises the values:

if (scalar values %cache > 10_000) {
    prune(\%cache);
}

Edge cases#

  • Aliasing is the feature and the footgun. for (values %h) gives you aliases, not copies. A harmless-looking s/// inside such a loop rewrites the hash. If you want copies, assign first: my @v = values %h; for (@v) { ... }.

  • Hash order is randomised. Perl 5.18+ randomises the traversal order per-hash. Two hashes built from the same keys can yield values in different orders. Never rely on the order for anything that leaves the process — serialise via sort keys if you need stability.

  • Order is stable only while the hash is unmodified. Insertions and deletions may permute the order. The one documented exception is deleting the key most recently returned by each or keys, which leaves the remaining order intact.

  • keys, values, each agree. For a hash that has not been modified between calls, keys %h and values %h produce corresponding lists in the same order — (keys %h)[$i] and (values %h)[$i] name the same entry.

  • Array form behaves like @array plus a reset. values @a in list context is equivalent to @a, with the side effect of resetting the array’s iterator. For the iterator-reset alone, keys @a in void context is the conventional choice.

  • Empty hash or array returns the empty list in list context and 0 in scalar context. No warning, no error.

  • Tied hashes. Behaviour is delegated to the tie class’s FIRSTKEY / NEXTKEY / FETCH methods. Order, aliasing, and iterator-reset semantics follow whatever the tie implementation provides — the pure-hash guarantees above do not automatically carry over.

  • Removed experiment: scalar argument. Perl 5.14–5.22 experimentally accepted values $ref; that experiment was removed in 5.24. Dereference explicitly: values %$ref, values @$ref.

  • Array support requires 5.12+. Running values @a on an older Perl raises a syntax error. Use use v5.12; at the top of a file that relies on array form to make the requirement explicit.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • keys — the key-side companion; same ordering rules, same iterator, scalar context returns the count

  • each — single-step iteration returning ($key, $value) pairs; shares the iterator that values resets

  • exists — test whether a key is present without triggering autovivification

  • delete — remove a key/value pair; deleting the most-recently-returned key of each or keys leaves the remaining traversal order intact

  • map — transform values into a derived list without mutating the hash (the non-aliasing alternative to for (values %h))

  • sort — pair with keys when you need a deterministic traversal order