[HRPM] scaler or array and why?

jeff jeff at alanne.com
Wed Aug 23 01:47:22 CDT 2000


Michael Theiss wrote:

> Question: I need to put all of parsed and interpolated output of
> master_htm.pl  page into a variable that will then be assigned to an array.

 Well, I have a couple of (maybe helpful) comments:

0. Always 'use strict'. Always. Always always always.'-w' is a good idea
too.

1. Anytime you find yourself writing the same code multiple times, it's
a good bet that you can genericize it down to one. Why not make all of
your PostIt() subs a single sub, and pass it arguments instead?
Something like:

   From the calling code:

my $filename =
"/home/alphaudt/www/cgi-bin/0/includes/onmouseover.shtml";
&post_it($filename);


   The sub:

sub post_it{
    my $filename = shift;
    open(FILE, $filename) or die "can't open $filename: $!\n";
    local $/ = undef;
    my $whole_file = <POST>;
    close(FILE) or die "Error closing $filename: $!\n";
    print $whole_file;
}


   Better yet, stuff the names of your files into an array and use that
to call the sub:

my @files = qw( /home/alphaudt/www/cgi-bin/0/includes/onmouseover.shtml
		/home/alphaudt/www/cgi-bin/0/includes/meta_data.shtml
		you_get_the_idea );

    Then just:

&post_it( $files[0] );
&post_it( $files[1] );

 This lets you change everything in one neat place, if you need to.



# Neat recursive explanation
2. A neat trick to slurp in the contents of a file is to make a local
copy of the $/ variable (the input record separator, normally a
newline). Instead of:

while (<POST>){$postit .=$_;}

you do:

 local $/ = undef;
 my $whole_file = <POST>; #slurp it all into one scalar 



3. Use here documents for printing multiple lines. Instead of:

print "Content-type: text/html\n\n";
print "<head>\n";
print "<!--START META DATA -->\n";

 do this:

print <<END;
Content-type: text/html

<head>
<!--START META DATA -->
END



4. The thing about saving it to a scalar is that your output is going to
STDOUT, not your script. You can get around this by wrapping the whole
thing in an eval{} block, like so:

my $output = eval{

print <<END;
Content-type: text/html

<head>
<!--START META DATA -->
END
...
&post_it( $files[0] );
...
&post_it( $files[1] );
...
 };


 I'm not sure what good this does you, since you end up with the entire
output in a scalar, but nowhere for it to go. Also keep in mind that
this approach can consume copious amounts of memory, since you're
stuffing everything into a variable.

 Reference the Camel book for more. Hope this helps.

 Jeff



More information about the Norfolk-pm mailing list