Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

exists

Tests whether a hash key or array index is present in the container.

Pops a key and a container (hash or array) from the stack. For hashes, checks whether the key is present (even if the associated value is undef). For arrays, checks whether the index is within bounds and the element has not been deleted. Pushes 1 (true) or 0 (false).

When the container is a stash (package symbol table accessed via %{"Package::"}), checks for the existence of any symbol type (scalar, array, hash, or code) with the given name.

Synopsis

if (exists $hash{$key})   { ... }
if (exists $array[$idx])  { ... }
if (exists $stash{$name}) { ... }   # stash symbol lookup

Implementation Notes

perl5: TOS is the result of helem (the SV slot itself). But our helem already consumed the key. We need to handle this differently. Actually, perl5 uses a special flag path. For exists, the stack has the helem op’s result. In p5 we handle it: TOS has the helem SV. exists returns true if the helem produced a non-undef SV. pp_exists — exists($h{key}).

perl5: Pp_exists (pp.c). Stack has hv_sv, key_sv. Returns &PL_sv_yes if key exists, &PL_sv_no otherwise.

See Also

PP runtime: exists | defined, delete, keys