Saturday, February 20, 2010

Programmer - What's the best way to conditionally include an element in a list?

Programmer Question

Possible ways:




  1. Using push:



    my @list;  
    push @list, 'foo' if $foo;
    push @list, 'bar' if $bar;

  2. Using the conditional operator:



    my @list = (  
    $foo ? 'foo' : (),
    $bar ? 'bar' : (),
    );

  3. Using the x!! Boolean list squash operator:



    my @list = (  
    ('foo') x!! $foo,
    ('bar') x!! $bar,
    );



Which one is better and why?

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails