Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: text munging utility

by jeffa (Bishop)
on Jan 26, 2004 at 22:01 UTC ( #324284=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://324284]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (9)
As of 2020-11-27 15:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?