Perl Advent Calendar 2009-12-24

Noëlvalue

by Jerrad Pierce

lvalue provides some supplementary syntax for defining Lvalue subroutines in such a way as to overcome the two objections from perlsub i.e;

nick@north# perl -l mod24.pl
Dasher, Dancer, Vixen, Comet, Cupid, Prancer, Dunder, Blixem
Dasher, Dancer, Vixen, Comet, Cupid, Prancer, Donner, Blitzen
expected reference to an array, you supplied a HASH at mod24.pl line 10.

One minor nit with it though, is that punctuation is forbidden between the get and set blocks, which means that code formatters can be confused (as perltidy was below) and the second block's contents will likely be over-indented in your editor contents will be over-indented in your editor. Fortunately, you can specify your blocks in whichever order you prefer, so if one is much shorter than the other you can list it second to reduce the visual impact of misindenting.

mod24.pl

   1 use lvalue;
   2 
   3 {
   4     # Make it a closure too
   5     my $ary = [qw/Dasher Dancer Vixen Comet Cupid Prancer Dunder Blixem/];
   6 
   7     sub reindeer : lvalue {
   8       set {
   9 	my $val = shift;
  10 	die('expected reference to an array, you supplied a ', ref $val)
  11 	  unless ref $val eq 'ARRAY';
  12 	return $ary = $val;
  13       }
  14       get {
  15 	return join ', ', @{$ary};
  16       }
  17     }
  18 }
  19 
  20 print reindeer();
  21 print reindeer() = [qw/Dasher Dancer Vixen Comet Cupid Prancer Donner Blitzen/];
  22 print reindeer() = {foo=>'bar'};
View Source (POD)