I need to find a way to manipulate a filehandle as a variable.

I know (or believe I know) several things

  1. Filehandles are scoped the same way variables are
  2. Despite this similarity, you can't assign filehandles in the same way you do variables, because that reads from the handle instead

My problem is that I want to open a file inside a subroutine, but have the resulting filehandle be available for use everywhere after the function is called. For example...

#example 1 HANDLE = &callafunction(); # what is HANDLE? I don't know print HANDLE "This prints to file.txt\n"; sub callafunction { open ( OUT, "file.txt" ) or die ( "open no worky!: $!" ); # somehow "return" OUT so it gets aliased to HANDLE }

Also, I may need to open several files in this subroutine, so I would like to be able to put these "file-handle-variables" into an array of some kind, and then return that like this...

#example 2 ( HANDLE1, HANDLE2 ) = &callafunction(); print HANDLE1 "This goes to file1.txt\n"; print HANDLE2 "This goes to file2.txt\n"; sub callafunction { open HANDLE1, "file1.txt" or die ( "open no worky!: $!" ); open HANDLE2, "file2.txt" or die ( "open no worky!: $!" ); my @array; # somehow push HANDLE1 and HANLDE2 onto @array @array; }

I used two examples because it occurred to me that it might be possible to do one of these tasks, but not the other (or someone might know the answer to one, and not the other).

Does anyone know how I can go about these tasks, if either of them are possible?

Thanks in advance.


In reply to returning filehandles by DeusVult

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.