Thursday, June 12, 2008

PERL - Passing Filehandles to Subroutines

#!/usr/bin/perl
use warnings;
use strict;

open(NAME, "./names") or die " Failed to open tns_names file : $! \n ";
open(PASS, "./pass") or die " Failed to open tns_pass file : $! \n ";

&process_names(*NAME);
&process_pass(*PASS);

close NAME;
close PASS;


sub process_names($)
{
local (*h) = shift;
while()
{
chomp $_;
print $_ . "\n";
}

}


sub process_pass($)
{
local (*h) = shift;
while()
{
chomp $_;
print $_ . "\n";
}
}

2 comments:

Michael said...

The refs to the passed file handles aren't shown because they are in angle brackets and treated as unrecognised HTML. Use &gt; for > and &lt; for <

Michael said...

Also, see http://perl.plover.com/local.html (Marginal Uses for FileHandles) for how to do this without using local.