Perl 5.8 cascading null checks

Say I have the following Groovy code:

String name = child.getParent()?.getParent()?.getName();

Please note that it getParent()may return null, in which case the code continues to work without null pointer exception exceptions.

Is there a way to do this clearly on one line in Perl 5.8? I am ready to write a general helper method to accomplish this.

I am faced with situations where I have several nested objects and I need to do something like:

my $name = $child && $child->getParent && $child->getParent->getParent && $child->getParent->getParent->getName;

Yes, it's on one line, but IMO is poisonous.

+4
source share
3 answers

In my opinion, your Groovy source code is always at the edge of readability. I would execute it differently, but a similar expression in Perl would be

my $name = (
    $node = $node->get_parent or
    $node = $node->get_parent or
    $node->get_name
);

+3

, ​​ eval:

my $name = eval { $child->getParent->getParent->getName }

last, ( {...} for(1) {...}):

my $name; { $name = (($child->getParent || last)->getParent || last)->getName }
0

It looks like you want to extract information from the DOM on an HTML page. For this, I recommend that you use the Perl module, which simply does this. Check out Mojo :: DOM

0
source

All Articles