perlmeditation
stefp
The following implements an enum a la C. It probably has been done
before and better. I welcome pointer, but this is not my point. Here I am obliged
to use twice the same pattern match. I can't even use <code>qr//</code> because I would have no way (at least in perl5) to get at the capture. [TheDamian] may had wanted
to save away the captures to restore them but $1, $2...
are read-only as far as the end-programmer is concerned.
I have not peeked at Damian's code but this [cpan://Switch] seems to me yet
another case for the scopeless eval.<p>
I already discussed at [id://179768], but there will never be enough shameless plugs in perlmonks for
<a href="http://dev.perl.org">Perl6 and parrot.
</a>
<code>
#! /usr/bin/perl
use strict;
use Switch 'Perl6';
use Carp;
sub enum {
my @enum = split /,/, $_[0];
my $i = 0;
for (@enum ) {
given ($_) {
when m/([A-Z]+\d*)(?:\s*=\s*(\d)+)?/i {
m/([A-Z]+\d*)(?:\s*=\s*(\d)+)?/i;
no strict;
$i = $2 if defined $2;
eval "sub $1() { $i }";
$i++;
}
else { croak qq(bad enum member syntax: "$_") }
}
}
}
enum "INFIX, PREFIX=4, SUFFIX" ;
print INFIX(), ":", PREFIX(), ":", SUFFIX(), "\n";
</code>
<p> -- <a href="/index.pl?node=stefp&lastnode_id=1072">
stefp</a> -- check out <a href="http://texmacs.org">TeXmacs</a>
<a href="http://alqua.com/tmresources/">wiki</a>