Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] How to pass a filehandle to a subroutine?

Expand Messages
  • hooyar66
    ... get the ... result of ... - I ... Many thanks guys I got it to work as: #!c:/perl/bin/perl.exe -w use strict; use diagnostics; my $fh;
    Message 1 of 4 , Jul 9 1:25 PM
    • 0 Attachment
      --- In perl-beginner@yahoogroups.com, Brad Lhotsky <brad@...> wrote:
      >
      > Ick. Don't use subroutine prototyping.
      >
      > open( my $fh, 'w', 'mydata.txt' )
      > or die "unable to open file: $!\n";
      >
      > pass_fh_($fh);
      >
      > sub pass_fh {
      > my $fh = shift;
      > }
      >
      > Using barewords for filehandles is not good practice. Always prefer
      > lexical scoping.
      >
      > On Mon, Jul 09, 2007 at 11:21:35PM +0530, Jabir Ahmed wrote:
      > > use strict;
      > > use diagnostics;
      > >
      > > open FH, ">mydat.txt";
      > >
      > > sub pass_fh(*);
      > >
      > > pass_fh(\FH);
      > >
      > > sub pass_fh(*)
      > > {
      > > my $MYFILE = shift @_;
      > > print $MYFILE "Filehandle was passed!";
      > > }
      > >
      > > ----- Original Message -----
      > > From: hooyar66
      > > To: perl-beginner@yahoogroups.com
      > > Sent: Monday, July 09, 2007 11:00 PM
      > > Subject: [PBML] How to pass a filehandle to a subroutine?
      > >
      > > I am trying to pass a filehandle to a subroutine but cannot
      get the
      > > syntax right. I have been reading about using 'prototypes' but
      > > something isn't sinking in... the test code below is the
      result of
      > > that research - it will not work with or without 'use strict'
      - I
      > > would prefer to keep 'strict'.
      > >
      > > Any help is gratefully appreciated
      > >
      > > Thanks
      > > NJH
      > >
      > > #!c:/perl/bin/perl.exe -w
      > >
      > > use strict;
      > > use diagnostics;
      > >
      > > open FH, ">mydat.txt";
      > >
      > > sub pass_fh(*);
      > >
      > > pass_fh(FH);
      > >
      > > sub pass_fh(*)
      > > {
      > > my $MYFILE = shift @_;
      > > print $MYFILE "Filehandle was passed!";
      > > }
      > >
      > > [Non-text portions of this message have been removed]
      > >
      > >
      >
      > --
      > Brad Lhotsky
      >

      Many thanks guys

      I got it to work as:

      #!c:/perl/bin/perl.exe -w

      use strict;
      use diagnostics;

      my $fh;
      open($fh,'>mydata.txt')
      or die "unable to open file: $!\n";

      print $fh "Text from main\n";

      pass_fh($fh);

      sub pass_fh {
      my $fh = shift;
      print $fh "Text from sub\n";
      }
    Your message has been successfully submitted and would be delivered to recipients shortly.