in reply to Re: What does 'last OP;' do?
in thread What does 'last OP;' do?

If you initialize %STR_OPS and %NUM_OPS as follows:

# Do this once for efficiency. use vars qw(%NUM_OPS %STR_OPS); BEGIN { $NUM_OPS{$_} = eval "sub { \$_[0] $_ \$_[1] }" foreach (qw(< <= != >= > ==)); $STR_OPS{$_} = eval "sub { \$_[0] $_ \$_[1] }" foreach (qw(lt le ne ge gt eq)); }

Then the snippet boils down to:

$v = ${$pairs{$ca}}[0]; if ($types{$ca}) { $v = 0 unless defined $v; $op = $NUM_OPS{$co}; } else { $v = '' unless defined $v; $op = $STR_OPS{$co}; } die("Undefined operation $co.\n") unless $op; $r &= $op->($v, $cv);

It's even more robust than the original.

Replies are listed 'Best First'.
Re^3: What does 'last OP;' do?
by TomDLux (Vicar) on Jan 22, 2005 at 21:29 UTC

    I would go further, and make a single array or hash containing all of %NUM_OPS and %STR_OPS. For example:

    BEGIN { $OPS{'num'}{$_} = eval "sub { \$_[0] $_ \$_[1] }" foreach (qw(< <= != >= > ==)); $OPS{'str'}{$_} = eval "sub { \$_[0] $_ \$_[1] }" foreach (qw(lt le ne ge gt eq)); } # ... and later ... $v = ${$pairs{$ca}}[0]; my $op_type = $types{$ca} ? 'num' : 'str'; my $op = $OPS{$op_type}{$co}; die("Undefined operation $co.\n") unless $op; $r &= $op->($v, $cv);

    It would be even better if you could alter the code which sets up %types, so that instead of true and false values, it could store the strings we need: 'num' or 'str'.

    --
    TTTATCGGTCGTTATATAGATGTTTGCA