Hi all,

I've been using Perl for the last 14 months (where I was a heavy Awk user prior to that) and now want to graduate to making my own packages. Defining the package seems fairly straight-forward using the template from perlmod, but I'm having difficulty trying to globalize my filehandle as I would rather not pass the filehandle explicitly into each of my subroutines, as each one will write into the file (there are ~15 small subroutines.)

Main code:

#!/usr/bin/env perl use strict; use warnings; #use diagnostics; use MyPkgDirectory::MyPkg; my $wmode = '>'; my $rmode = '<'; my $filename = "zz_file.txt"; #my $FH_text_W; # this doesn't work, lexical? our $FH_text_W; # can I globalize my filehandle? open($FH_text_W, $wmode, $filename) || die "ERROR: cannot open $filena +me for writing $!"; print "Debug: Filehandle is: $FH_text_W\n"; &samplewrite(10, "foofoo"); # I don't want to pass in the FH! close ($FH_text_W);

My package:

package MyPkgDirectory::MyPkg; # assumes MyPkgDirectory/MyPkg.pm use strict; use warnings; BEGIN { require Exporter; our $VERSION = 1.00; our @ISA = qw(Exporter); our @EXPORT = qw(samplewrite); } my $FH_text_W = $main::FH_text_W; #my $FH_text_W; sub samplewrite { my ($ver, $sheet) = @_; print "Debug: Version $ver\n"; print "Debug: SHEET $sheet\n"; print $FH_text_W "Version $ver\n"; # Bombs out here print $FH_text_W "SHEET $sheet\n"; # and here too } END { } 1;

The output when I run my testcase and the ensuing error message I'm getting is as follows:

Debug: Filehandle is: GLOB(0x3f8dac)

Debug: Version 10

Debug: SHEET foofoo

Can't use an undefined value as a symbol reference at MyPkgDirectory/MyPkg.pm line 21.

Thanks in advance,

Joe

In reply to Globalize Filehandles and Visibility in Packages? by smknjoe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.