in reply to Dynamic function chains?

First of all, exp isn't the same as 2^x (it's e^x). (Found that when I tested the code.)
#!/usr/bin/perl use strict; use warnings; my %opts = ( power => sub { exp( $_[0] )}, log2 => sub { log( $_[0] )/log(2.0) }, loge => sub { log( $_[0] ) }, log10 => sub { log( $_[0] )/log(10.0) }, round => sub { int($_[0] + ($_[0] <=> 0)*0.5) }, trunc => sub { int $_[0] }, f1 => sub { sprintf "%.1f", $_[0] }, f2 => sub { sprintf "%.2f", $_[0] }, f3 => sub { sprintf "%.3f", $_[0] }, f4 => sub { sprintf "%.4f", $_[0] }, f5 => sub { sprintf "%.5f", $_[0] }, ); my $func = sub {$_[0]}; for my $arg (reverse @ARGV){ if (defined $opts{$arg}){ my $localfunc = $func; $func = sub {$opts{$arg}->($localfunc->($_[0]))}; } else { print STDERR "Unknown arg: $arg\n"; } } while (<> ) { chomp; my @in = split; print shift(@in), " "; print join(" ", map { $func->($_) } @in), "\n"; }

Replies are listed 'Best First'.
Re^2: Dynamic function chains?
by keymon (Beadle) on Sep 15, 2004 at 15:00 UTC
    First of all, exp isn't the same as 2^x (it's e^x). (Found that when I tested the code.)

    My bad! I was trying to keep the output simple.

    I like the usage of a hash to store the subs, and also the cute (and much less verbose) &round.
    Thanks!