NAME

Syntax::Infix::OptionalChain - a safe-navigation ?-> operator for objects, hashes and arrays

VERSION

Version 0.01

SYNOPSIS

use Syntax::Infix::OptionalChain;

my $name = $maybe?->profile?->name // 'anonymous';

# one operator, three kinds of right-hand side, chosen at run time:
$object?->method  # $object->method     (blessed -> can -> method call)
$hashref?->key    # $hashref->{key}     (HASH ref -> element)
$arrayref?->0     # $arrayref->[0]      (ARRAY ref -> element)

# mixed chains short-circuit at the first undef, with no autovivification
# and no "Can't use an undefined value" deaths:
my $port = $config?->servers?->0?->port // 8080;

DESCRIPTION

Installs a lexically-scoped infix operator ?-> that walks one step into its left operand and short-circuits to undef the moment that operand is undefined. The right-hand side is a bareword, and how it is used depends on what the left operand is at run time:

  • a blessed object with that method -> a method call, $obj->name;

  • a HASH reference -> a hash element, $h->{name};

  • an ARRAY reference -> an array element, $a->[name] (the bareword is used as the index, so write a number: $a ?-> 0);

  • undef -> undef, ending the chain harmlessly.

A blessed object is tried as a method call first; if it has no such method it falls through to structural access, so a blessed hashref or arrayref is indexed by the bareword just like a plain one. (A consequence: an unknown name on a blessed hashref is a key lookup, typically undef, not a fatal unknown-method error.)

Because ?-> is left-associative and binds tightly (like *), chains read left to right and combine naturally with // for defaults. A defined value that can be navigated no further -- a plain string, or a blessed/plain ref that is neither a hash nor an array -- is a genuine error and croaks, rather than being silently swallowed.

The operator is lexically scoped: it exists only in the file or block that used the module, and no Syntax::Infix::OptionalChain; removes it early.

Limitations

The right-hand side is a bareword captured at compile time, so it is a literal method name / key / non-negative integer index. Argument lists ($o ?-> meth(@args)), negative indices and computed keys are not supported; reach for an explicit ->{...} / ->[...] there.

Perl version

Requires perl 5.38 or newer -- the version that added the PL_infix_plugin hook Infix::Custom builds on. As the operator is the module's entire reason to exist, the distribution does not install on older perls.

SEE ALSO

Infix::Custom -- the general custom-infix-operator mechanism this is built on.

AUTHOR

LNATION <email@lnation.org>

LICENSE AND COPYRIGHT

This software is Copyright (c) 2026 by LNATION <email@lnation.org>.

This is free software, licensed under The Artistic License 2.0 (GPL Compatible).