Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

I feel like a broken record

Are you like me, and often find yourself wanting to include an element in a list conditionally (often depending on whether it is defined)?

F.ex., I may want to construct a URI which has a number of moving parts.

  • In the simplest case, it may look like, where doc is a controller in the web app.
  • To link a specific item, the URI might be
  • Some controllers are broken down further, giving things like
  • The app supports multiple sites, so I might also have something like
  • To get the editing interface, you need to prefix the whole shebang accordingly, ie. for the joebob subsite:

There are two dead obvious approaches to write this in Perl:

  1. The ugly push-based version:

    my @part = ( '' ); push @part, 'admin' if $is_admin_link; push @part, $subsite if defined $subsite; push @part, $mode; push @part, $id if defined $id; push @part, $submode if defined $submode; my $uri = join '/', @parts;
  2. The nicer approach with a ternary:

    # [updated: originally had `'admin' ? $is_admin_link : ()`] my @part = ( '', ( $is_admin_link ? 'admin' : () ), ( defined $subsite ? $subsite : () ), $mode, ( defined $id ? $id : () ), ( defined $submode ? $submode : () ), ); my $uri = join '/', @part;

But both approaches require you to repeat yourself unncessarily. In the push case, you have to repeat the push @part bit, and in the ternary case, you have to supply : () as an else clause for every case.

Enter x!!

Obviously, this is a composite operator, consisting of x and two ! negations.

The double negation is there to forcibly convert the right side to a boolean value with the same truthness as the original value:

$a = undef; print $a ? 'true' : 'false'; # prints 'false' print $a; # prints '' and warns $a = 0; print $a ? 'true' : 'false'; # prints 'false' print $a; # prints '0' $a = 'abc'; print $a ? 'true' : 'false'; # prints 'true' print $a; # prints 'abc' # whereas $a = undef; print !!$a ? 'true' : 'false'; # prints 'false' print !!$a; # prints '' without warning $a = 0; print !!$a ? 'true' : 'false'; # prints 'false' print !!$a; # prints '' $a = 'abc'; print !!$a ? 'true' : 'false'; # prints 'true' print !!$a; # prints 1

So the !! will force anything that shows up on the right side to be either 1 or !1.

The x is, of course, Perl’s repetition operator:

@_ = ( 'a' ) x 4; print join ':', @_; # prints 'a:a:a:a' print scalar @_; # prints '4'

Of interest to us are the cases where the number of repetitions is 1 or 0:

@_ = ( 'a' ) x 1; print join ':', @_; # prints 'a' print scalar @_; # prints '1' @_ = ( 'a' ) x 0; print join ':', @_; # prints '' print scalar @_; # prints '0'

Since boolean values in Perl are either 1 or !1, that means ( $something ) x $boolean will do exactly what we want. And we can force everything to be a boolean using the !! double negative. That is how we get x!!.

Update: caveat codor – as ikegami emphasises, the parens are required! ( $something ) x $boolean does a very different thing from $something x $boolean. I knew this, but forgot to harp on it. (Yes, this difference is too subtle. In Perl 6, there will therefore be two different operators, x for strings and xx for lists.)

Bottom line: the example I gave can be written like this:

my @part = ( '', ( 'admin' ) x!! $is_admin_link, ( $subsite ) x!! defined $subsite, $mode, ( $id ) x!! defined $id, ( $submode ) x!! defined $submode, ); my $uri = join '/', @parts;

Neato! Not only is it nicer, but I also find that x!! has a beautifully evocative quality. :-)

Update: but note that ( $x ) x!! $cond differs from $cond ? $x : () in shortcircuiting behaviour: the ternary will avoid evaluating $x if $cond is false, but x!! will always evaluate it.

Conventional notes

You’ll notice that defined always returns a boolean anyway, so the !! isn’t actually necessary in three of our cases, and might not be necessary in the first one either.

However, I find that one should use x!! anyway, for two reasons:

  1. It documents intent. Using x!! clearly signals that this is not just a repetition.
  2. It protects you from errors. If the value of $is_admin_link is 2 for some reason, it is still true according to Perl, but in that case ( 'admin' ) x $is_admin_link (without !!) will yield a very different result from ( 'admin' ) x!! $is_admin_link (with !!).


So there you have it. If you want to conditionally include a sub-list within a larger list, you can use the composite x!! operator express exactly that.

Makeshifts last the longest.

In reply to Secret Perl Operators: the boolean list squash operator, x!! by Aristotle

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others taking refuge in the Monastery: (5)
    As of 2018-06-20 12:19 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (116 votes). Check out past polls.