sub contents { open (FH, "< $FileInfoName") or die "Can't open $FileInfoName for re +ad: $!"; my @lines = <FH>; # return @lines; # 1st problem: in scalar context, number of lines is + returned # 2nd problem: next line is never reached close FH or die "Cannot close $FileInfoName: $!"; return join("", @lines); # fix: one big string with all lines concate +nated # See also File::Slurp }

See module File::Basename to extract the directory name (dirname()) from the path, you already have. See module Cwd to get current working directory - if required.

Update: oops - you wanted contents() to return an array (Perl: list) -- then you can keep the return @lines; (in last line) and change the callers context as toolic suggested.

Maybe two other suggestions?

  • Avoid globals like $FileInfoName, use a parameter to contents() instead.
  • A more contemporary way is the three-arg-open plus avoiding globs like FH:
    e.g: open(my $file, '<', $FileInfoName) or die "..."; my @lines = <$file>; ...
    (and maybe chose a better name than $file (as I did here ;-) - something that is meaningful in the given context.

  • In reply to Re: Subroutines....return directory file is in and return contents in array by Perlbotics
    in thread Subroutines....return directory file is in and return contents in array by csorrentini

    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.