I want to create a subroutine that prints a "standard" header that I need for text files. I would like to pass the FILEHANDLE in to this subroutine.
Not really an answer to your question, but it sprang to mind that you can write custom layers, and that PerlIO::via eases the task when implementing them in Perl, as opposed to C. Since I had never fiddled with this kinda things (experts, please point out any shortcoming/error/whatever), I quickly checked the docs and concocted the following example:
# -*- Perl -*- use strict; use warnings; package PerlIO::via::MyHeader; our $VERSION = '0.01'; use Carp (); sub PUSHED { my ($class,$mode)=@_; Carp::croak __PACKAGE__, " can be used only for writing to file." unless $mode =~ /w/; bless \(my $x), $class; } my %done; sub WRITE { my ($obj,$buf,$fh)=@_; print $fh ($done{$obj}++ ? '' : <<' HEADER'), $buf; START_OF_FILE DATEFORMAT=YYYYMMDD DECIMALSEPARATOR=. HEADER } 1; __END__
Admittedly, I used somewhat of an stunt to just print a header, but there's no hook that I can see to do that in a clean way. Be aware that it will slow down your prints, albeit probably in an unnoticeable manner under most common circumstances, but in case performance does matter instead, well... it will matter!
A test script:
#!/usr/bin/perl use strict; use warnings; use lib '.'; use PerlIO::via::MyHeader; open my $fh1, '>:via(MyHeader)', "test1" or die "Can't open 'test1': $!\n"; open my $fh2, '>:via(MyHeader)', "test2" or die "Can't open 'test2': $!\n"; print $fh1 "foo\n"; print $fh1 "bar\n"; print $fh2 "foo\n"; print $fh2 "bar\n"; __END__
And the proof of the pudding, which is in the eating:
C:\temp>perl testmh.pl C:\temp>diff test1 test2 C:\temp>cat test1 START_OF_FILE DATEFORMAT=YYYYMMDD DECIMALSEPARATOR=. foo bar
All in all, it was kinda funny. And instructive, it will be even more with some feedback.
Update: I suppose I should cleanup the %done hash on CLOSE(), but let's fake it had been left as an exercise to the reader.
In reply to Re: passing a file handle to a subroutine
by blazar
in thread passing a file handle to a subroutine
by kevind0718
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |