Docendo discimus


  • Calendar

    December 2021
    M T W T F S S
  • Archives

  • Recent Posts

  • Bling

Posts Tagged ‘map’

Catalyst is easy – scary interlude

Posted by brunorc on June 9, 2009

Last time I tried to show how one can write quick and dirty code in Catalyst. Nothing fancy, some old stuff with so called “here doc” syntax. Let me get back to this example and explain – step by step – how the monster can be born.

The idea was to show the list in HTML. For this there is a list needed, and some processing. In the end there is a string (a scalar variable), containing all the list with HTML ornaments:

      my @items = ( 'beer', 'bacon', 'pierogi' );  
      my $list = '';  
      foreach my $item ( @items ) {  
          $list .= "<li>$item</li>\n";  

Actually it can be shorter. First of all, there is a qw operator, which produces the list of quoted words (thus its name). And since there’s no need to store the list, it can be produced “on the fly”:

      my $list = '';  
      foreach my $item ( qw/beer bacon pierogi/  ) {  
          $list .= "<li>$item</li>\n";  

Now there’s a list and a block of code. Incidentally, Perl also offers a function called map which operates on a block of code and a list:

      my @html_items = map { "<li>$_</li>" } qw/beer bacon pierogi/;
      my $list = join( "\n", @html_items );

In this case it is quite reasonable to ask map to return a list. The list is then passed to join, which (you guessed it!) joins the elements of a list. And yes, you will need split to actually split a string into a list of items.

What about the ugly $_? This is the special variable meaning “this” or “it”. As you may already know, English is not my native language, so forgive me, I won’t get into details. If you prefer, you can also treat $_ as “every” or “each one of”:

map { burn $_ } @heretic_books;

And no, Perl doesn’t provide the burn function.

So… is it possible to make this code even shorter? Yes, we can get rid of temporary list of HTML items. The final code would have only one line:

      my $list = join( "\n", map { "<li>$_</li>" } qw/beer bacon pierogi/ );

Of course, it doesn’t have to, since some indentation would clearly improve its legibility:

my $list = join( "\n", 
                map { "<li>$_</li>" } 
                    qw/beer bacon pierogi/ );

There is no need to write such code, though. The beauty of Perl lies in its patience and flexibility. It will wait for the programmer, providing him with all the necessary tools, so he would get his job done. Of course Perl will also provide her, since it’s definitely less sexist than I am. And if at any moment programmer should decide to make his code terser, Perl will provide him with the right tool for this task. But it is up to programmer to decide, not up to language.

Posted in Catalyst for intimidated | Tagged: , , , , , , | Leave a Comment »