CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Read a FIle

 



mike_robb
Novice

Mar 16, 2001, 8:04 PM

Post #1 of 3 (205 views)
Read a FIle Can't Post

What is the best (quickest) way to get the contents of a file passed through to perl script to the web browser?

I know how to open a file for reading, but I only know how to dump that into an array and then loop through the array and build a long string. I then put this string into a hash which is used elsewhere to put it into the web page that is built.

Is there a better way to get the contents of a file into a string?

---

what i am doing:

sub get_topmenu{
my ($template) = @_;
open(HEADFILE,"< $template->{'config'}->{'headfile'}") or die "header file not opened: $!";
my @temp=<HEADFILE>;
my $i;
my $x="";
foreach $i (@temp){$x.=$i;}
$template->{'topmenu'} = $x;
}

Any ideas?

TIA!



rGeoffrey
User / Moderator

Mar 16, 2001, 10:02 PM

Post #2 of 3 (201 views)
Re: Read a FIle [In reply to] Can't Post

Your function call can be written as this one line if you have a Slurp_File function to take a $file and give the $string of the whole file content...


Code
$template->{'topmenu'} = &Slurp_File ($template->{'config'}->{'headfile'});

Now how to write the &Slurp_File to get the whole thing. Here are three alternatives that will do it...


Code
sub Slurp_File 
{
my ($file) = @_;
open DATA, $file or die "can't open $file: $!";
my $data = join ('', <DATA>);
close DATA;

return ($data)
}

sub Slurp_File
{
my ($file) = @_;
local $/;
open DATA, $file or die "can't open $file: $!";
my $data = <DATA>;
close DATA;

return ($data)
}

sub Slurp_File
{
my ($file) = @_;
open DATA, $file or die "can't open $file: $!";
my $data = do { local $/, <DATA> };
close DATA;

return ($data)
}

The first one is closest to what you did, read in each row, and join them together to form the string.

The other two are variations on a theme and change the value of the input record separator $/ from the default of "\n" to undefined. This allows us to slurp the whole file in one read because it will not stop at each "\n". The last one hides the change to $/ inside the do block to further insulate the change.

Remember that if you change $/ and don't localize the change inside a block, then strange things might happen other places that use $/, like reading other files.

--
Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?


mike_robb
Novice

Mar 19, 2001, 4:57 PM

Post #3 of 3 (185 views)
Re: Read a FIle [In reply to] Can't Post

thanks for the info!


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives