bkiahg has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I am looking for a more efficient way of writing from a file handle. What I am doing is opening a dat file and printing it to a webpage. This is how I've been doing it so far.
open (AP_MENU, "/web/aps/ap_menu.dat") or die "Cannot open: $!"; @fileinput_ap = <AP_MENU>; for ($i = 0; $i <= $#fileinput_ap; $i++) { print "$fileinput_ap[$i]" +} close (AP_MENU) or die "Cannot close: $!";
Is there a more efficient way than reading everything into an array?

Replies are listed 'Best First'.
Re: Printing From a File Handle
by haoess (Curate) on Apr 28, 2004 at 20:22 UTC
    @fileinput_ap = <AP_MENU>; for ($i = 0; $i <= $#fileinput_ap; $i++) { print "$fileinput_ap[$i]" +}

    This can be done more perlish:

    while( <AP_MENU> ) { print; }
    or shorter:
    print while <AP_MENU>;

    If you just want to print an entire file, you can use print in array context

    print <AP_MENU>;
    -- Frank
      Is there anyway to add html formatting to it? e.g.
      print while "<AP_MENU><br>";
        TIMTOWTDI:
        # shortest print "$_<br />" while <AP_MENU>; # show what you mean { local $\ = "<br />"; print while <AP_MENU>; } # more readable? foreach my $line (<FILE>) { print $line, "<br />"; }
        -- Frank

        Still more ways to do it:

        # list processing print map "$_<br />", <AP_MENU>; # more abuse of special variables { local $, = "<br />"; print <AP_MENU>, ''; }

        If you are reading in any old file for display in an HTML page, you will want to do at least minimal escaping of special characters, too:

        while ( <AP_MENU> ) { # protect against most egregious HTML violations s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g; # remove trailing whitespace so the <br /> is on # the same line as main text s/\s+$//; print "$_<br />\n"; }
        #!/usr/bin/perl print "Content-type: text/html\n\n"; print <<top; <html> <head><title>Some Title</title></head> <body bgcolor="#000000"> top print "<font color=\"#FFFFFF\">$_</font><br>" for <DATA>; print <<bottom; </body> </html> bottom __DATA__ Test Test Again One More Test!
        You can see it work here.

        www.perlskripts.com
      while ( <LOG> ) { print "$_<br>" } does the trick.
Re: Printing From a File Handle
by b10m (Vicar) on Apr 28, 2004 at 20:14 UTC

    This is a way:

    open AP_MENU, "</web/aps/ap_menu.dat" or die "Cannot open: $!"; print <AP_MENU>; close AP_MENU or die "Cannot close: $!";
    --
    b10m

    All code is usually tested, but rarely trusted.
      or print while <AP_MENU>; to avoid whole-file slurp-and-dump.

      The PerlMonk tr/// Advocate
Re: Printing From a File Handle
by Anomynous Monk (Scribe) on Apr 28, 2004 at 22:52 UTC