A good way to approach this is to pass in the filehandle as one of the parameters. You can pass it from the caller either using the syntax the previous reply used, or by using the IO::File class to manage your open filehandles. As for the subroutine itself:

sub ReadBytes { my $fh = shift; my $num = shift || 1; # Default to 1 byte instead of error return undef unless ($fh); my $bytes; return undef unless (read($fh, $bytes, $num)); unpack("C$num", $bytes); }

Note that you don't need the for-loop, since both read() and unpack() can use the byte-count you already have. This routine isn't very helpful to the caller in error cases, you may want to do something cleaner with the two points where undef is being returned.

--rjray


In reply to Re: Nested subs - inherently evil? by rjray
in thread Nested subs - inherently evil? by myocom

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.