keymon has asked for the wisdom of the Perl Monks concerning the following question:
1 0 0 0 1 1 1 2 2 2 1 2 0 1 0 0 0 1 3 2 3 4 5 6 0 1 2and the operation is "power" (2^x), then the output would be:
1 1 1 1 2 2 2 4 4 2 2 4 1 2 1 1 1 2 3 4 8 16 32 64 1 2 4Operations can be "power", "log2", "loge", "log10", "round", etc. They can be specified multiple times too.
Here is what I came up with; is there a better (more efficient, cuter, whatever) way to do this? (What am I thinking; obviously there are better ways to do this, after all, this is Perl!!)
use Getopt::Long; sub power { return exp( $_[0] ) } sub log2 { return log( $_[0] )/log(2.0) } sub loge { return log( $_[0] ) } sub log10 { return log( $_[0] )/log(10.0) } sub round { my $n = shift; return int($n + 0.5) if ($n >= 0); return int($n - 0.5); } sub trunc { return int($_[0]) } sub f1 { return sprintf "%.1f", $_[0] } sub f2 { return sprintf "%.2f", $_[0] } sub f3 { return sprintf "%.3f", $_[0] } sub f4 { return sprintf "%.4f", $_[0] } sub f5 { return sprintf "%.5f", $_[0] } sub closure { my($sub, $arg) = @_; return sub { $sub->( &$arg ) } } my %opts = map { $_ => 1 } qw( power log2 loge log10 round trunc f1 f +2 f3 f4 f5 ); my $func = sub { return shift }; while (my $arg = pop(@ARGV) ) { $arg =~ s/^\-+//; if (defined ($opts{$arg})) { $func = closure( eval '\&' . $arg , $func ); } else { print STDERR "Unknown arg: $arg\n"; } } while (<STDIN> ) { chop; my @in = split; print shift(@in), " "; print join(" ", map { $func->($_) } @in), "\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Dynamic function chains?
by broquaint (Abbot) on Sep 15, 2004 at 12:48 UTC | |
|
Re: Dynamic function chains?
by Eimi Metamorphoumai (Deacon) on Sep 15, 2004 at 13:13 UTC | |
by keymon (Beadle) on Sep 15, 2004 at 15:00 UTC | |
|
Re: Dynamic function chains?
by tmoertel (Chaplain) on Sep 15, 2004 at 16:52 UTC | |
|
Re: Dynamic function chains?
by BrowserUk (Patriarch) on Sep 15, 2004 at 13:16 UTC | |
by keymon (Beadle) on Sep 15, 2004 at 15:08 UTC | |
by BrowserUk (Patriarch) on Sep 15, 2004 at 15:26 UTC | |
|
Re: Dynamic function chains?
by dave_the_m (Monsignor) on Sep 15, 2004 at 12:38 UTC | |
|
Re: Dynamic function chains?
by Roy Johnson (Monsignor) on Sep 15, 2004 at 16:08 UTC |