Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

What's the right way to write this:
defined($exceptions{$user}) ? (join " ",@{$exceptions{$user}} : ""
...I had initially written @{$exceptions{$user}}, which was short and sweet. But that fails if $user isn't a key of %exceptions. It seems overly complicated and verbose to have to check to see if $exceptions{$user} is defined before treating it as an array reference.

Replies are listed 'Best First'.
Re: overcoming undef as Array ref
by ysth (Canon) on Mar 29, 2007 at 21:55 UTC
    @{$exceptions{$user}||[]}
    But I suspect that code occurs in a larger block that could stand to have an if ( exists $exceptions{$user} ) or similar.
      @{$exceptions{$user}||[]}
      Ah, that looks like a better answer.
      But I suspect...
      Your suspicion detection algorithm is faulty. That expression is returned from a subroutine. No larger context.
Re: overcoming undef as Array ref
by rlb3 (Deacon) on Mar 29, 2007 at 21:42 UTC
    You might want 'exists' instead of 'defined'.
    exists ($exceptions{$user}) ? (join " ",@{$exceptions{$user}} : ""