http://qs321.pair.com?node_id=324284


in reply to text munging utility

# generate numeric comparison routines sub build_num_comp { my ($cexp, $cval) = @_; if ($cexp eq 'gt') { return sub { return ($_[0] > $cval); } } elsif($cexp eq 'lt') { return sub { return ($_[0] < $cval); } } elsif($cexp eq 'ge') { return sub { return ($_[0] >= $cval); } } elsif($cexp eq 'le') { return sub { return ($_[0] <= $cval); } } elsif($cexp eq 'eq') { return sub { return ($_[0] == $cval); } } elsif($cexp eq 'ne') { return sub { return ($_[0] != $cval); } } elsif($cexp eq 're') { return sub { return ($_[0] =~ /$cval/); } } elsif($cexp eq 'nr') { return sub { return ($_[0] !~ /$cval/); } } else { print "Invalid comparison, use ax -h for help.\n"; exit(1); } }
Why are you writing your own little mini-language there? Why not just use Perl's given operators for comparison? Creative use of eval yields:
sub build_num_comp { my $truth = eval "@_"; die "Invalid comparison, use ax -h for help.\n" if $@; return sub { $truth }; } print build_num_comp(5,'==',5)->() ? 'yes' : 'no'; print build_num_comp(5,'!=',5)->() ? 'yes' : 'no';
Work smart, not hard. ;)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: Re: text munging utility
by robobunny (Friar) on Jan 27, 2004 at 15:41 UTC
    Thanks, that's much tidier :) My reason for that nasty mess was to avoid putting special shell characters on the command line, but since that argument needs quotes around it anyway, it's probably fine.