Thursday 18 August 2011

Passing Files as Arguments

The Glob method of passing files is very Perlistic, and as such appears incredibly inobvious to general purpose programmers not using Perl on a regular basis. The Glob method is useful when retrofitting file passing in programs using Perl's syntax. If you're starting fresh, consider filehandles.

Here's the Glob method:

sub printFile($)
{
my $fileHandle = $_[0];
while (<$fileHandle>)
{
my $line = $_;
chomp($line);
print "$line\n";
}
}

open(MYINPUTFILE,"<filename");

printFile(\*MYINPUTFILE);
close(MYINPUTFILE);


Output files work similarly.

If you need to assign the glob to an actual variable, you can do that also. The code in the subroutine remains the same, and the following is the code doing the passing:

open(MYINPUTFILE, "<filename");
my $fileGlob = \*MYINPUTFILE;
printFile($fileGlob);
close(MYINPUTFILE);

No comments:

Post a Comment

Tweets by @sriramperumalla