Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://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 http://example.net/app/doc, where doc is a controller in the web app.
  • To link a specific item, the URI might be http://example.net/app/doc/42
  • Some controllers are broken down further, giving things like http://example.net/app/doc/42/notes
  • The app supports multiple sites, so I might also have something like http://example.net/app/joebob/doc
  • To get the editing interface, you need to prefix the whole shebang accordingly, ie. for the joebob subsite: http://example.net/app/admin/joebob/doc

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

  1. The ugly push-based version:

    my @part = ( 'http://example.net/app' ); 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 = ( 'http://example.net/app', ( $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 = ( 'http://example.net/app', ( '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 !!).

Conclusion

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

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-18 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found