On Nov 2, Mike Gargiullo said:
>OK I know Perl is the language that lets you do things several different
>ways. So with that having been said, how can I convert the while
>statement into a subroutine and pas the filehandles to it ?
I'd make a function that takes two filenames, and does the work. In fact,
if I felt frisky, I'd make a function that takes a block and two
filenames. I'll show both examples.
sub use_template {
my ($src, $dst) = @_;
local (*SRC, *DST);
open SRC, "< $src" or die "Can't read $src: $!";
open DST, "> $dst" or die "Can't write $dst: $!";
while (<SRC>) {
s/abcdefghijklm/$outid/; # do you need a /g modifier here?
print DST;
}
close DST;
close SRC;
}
You just call that with the pairs of filenames you want.
Here's the slightly more dynamic version:
sub use_template (&$$) {
my ($code, $src, $dst) = @_;
local (*SRC, *DST);
open SRC, "< $src" or die "Can't read $src: $!";
open DST, "> $dst" or die "Can't write $dst: $!";
my $oldfh = select SRC;
while (<SRC>) { $code->() }
select $oldfh;
close DST;
close SRC;
}
This function MUST BE DEFINED OR DECLARED before you use it. To declare
it, you can just say:
sub use_template (&$$);
near the beginning of your program. This works in a slightly different
fashion:
use_template { s/abcdefghijklm/$outid/; print } $input, $output;
You'll notice I send the actions as a block of code, and that I'm not
saying "print DST", but just "print". This is because the function
select()s DST as the default output filehandle for me.
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]