in reply to Why doesn't exist work with hash slices?

What would it even mean? Should it check if they all exist, or if any exist?

And that's why it doesn't exist. It's not clear what that should do, it's not clear what it does by looking at it, it's not something that's commonly needed, and it's easily done with slightly more code.

If you want to check if all of the elements exist, you can use

all { exists( $h{ $_ } ) } @keys

If you want to check if any of the elements exist, you can use

any { exists( $h{ $_ } ) } @keys

Replies are listed 'Best First'.
Re^2: Why doesn't exist work with hash slices?
by ysth (Canon) on Sep 21, 2025 at 16:46 UTC
    These are even efficient, with 5.42's experimental any and all operators. Before those, I'd almost never use List::Util's any/all/first, unless readability is super important or the body is doing something expensive like I/O, preferring something like:
    0 != grep exists $hash{$_}, @keys # any 0 == grep ! exists $hash{$_}, @keys # all

      While the new functions in core are a lot faster still, at least for any, List::Util has been way faster than grep.

      use strict; use warnings; use v5.42; use feature 'keyword_any'; no warnings 'experimental::keyword_any'; use List::Util; use Benchmark 'cmpthese'; my @list = 0 .. 1_000_000; my %hash = map { $_ => 1 } @list; cmpthese(-5, { 'grep' => sub { return 1 if 0 != grep exists $hash{$_}, @list }, 'List::Util::any' => sub { return 1 if List::Util::any { exists $ +hash{$_} } @list }, 'core any' => sub { return 1 if any { exists $hash{$_} } @list }, });
      Rate grep List::Util::any core any grep 14.1/s -- -98% -99% List::Util::any 634/s 4412% -- -46% core any 1168/s 8209% 84% --


      The way forward always starts with a minimal test.
        When all the keys exist, it's a million iterations against one, so it's not surprising. Use something like
        my %hash; @hash{ map int rand 1_000_000, 1 .. 1000 } = ();
        for a more realistic scenario (still impressive).

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]