M
Michele Dondi
I'm not sure the subject line is appropriate. Couldn't come up with
anything better...
Well, just to be definite (but not limited to the following example),
suppose I have to accomplish different tasks according to some cmd
line switches for a script. Say all of them involve 'while (<>)
{...}', so I do *not* want to test the switch for every iteration and
I do *not* want to repeat big portions of code either.
It seems to me that the "best" solution that doesn't clobber the main
logic of the program is something along the lines of the following
example. But I'm not sure if it is the "right(TM) thing" to do: can
you comment please?
#!/usr/bin/perl
# Oversimplified example
use strict;
use warnings;
use Term::ANSIColor qw/:constants/;
use Getopt::Std;
sub doit;
my %opt;
getopts 'c', \%opt;
if ($opt{'c'}) {
*doit = sub {
local $_=shift;
print if s/\b(foo)\b/RED.$1.RESET/ge
}
}
else {
*doit = sub {
local $_=shift;
print if /\bfoo\b/;
}
}
doit $_ while <>;
__END__
Also, as an aside, and since I'm very curious, having heard that
basically in Perl6 "everything will be an object", I wonder if it will
provide hooks for the beginning and the end of a sub, or possibly for
a label inside it, as in the following pseudo-code:
sub doit {
...
}
doit.END = {
print STDERR "$.: foo" if $foo;
} if $verbose;
Michele
anything better...
Well, just to be definite (but not limited to the following example),
suppose I have to accomplish different tasks according to some cmd
line switches for a script. Say all of them involve 'while (<>)
{...}', so I do *not* want to test the switch for every iteration and
I do *not* want to repeat big portions of code either.
It seems to me that the "best" solution that doesn't clobber the main
logic of the program is something along the lines of the following
example. But I'm not sure if it is the "right(TM) thing" to do: can
you comment please?
#!/usr/bin/perl
# Oversimplified example
use strict;
use warnings;
use Term::ANSIColor qw/:constants/;
use Getopt::Std;
sub doit;
my %opt;
getopts 'c', \%opt;
if ($opt{'c'}) {
*doit = sub {
local $_=shift;
print if s/\b(foo)\b/RED.$1.RESET/ge
}
}
else {
*doit = sub {
local $_=shift;
print if /\bfoo\b/;
}
}
doit $_ while <>;
__END__
Also, as an aside, and since I'm very curious, having heard that
basically in Perl6 "everything will be an object", I wonder if it will
provide hooks for the beginning and the end of a sub, or possibly for
a label inside it, as in the following pseudo-code:
sub doit {
...
}
doit.END = {
print STDERR "$.: foo" if $foo;
} if $verbose;
Michele