Read File To Var

[problem]

You want to read a file into a Perl variable.

[/problem]

[solution]

Following on from the Simple PHP demo of opening and reading contents of files, here is the Perl version.

Following script takes filename as a parameter, then opens it read-only and reads contents in data variable. Then it echoes a header and footer line, with the data in the middle.

[/solution]

[example]


#!/usr/bin/perl

$filename=$ARGV[0];

open($FH,") { $data.=$_; }

close($FH);

print "################# beginning of $filename ################\n";
print "$data";
print "\n################# end of $filename ################\n";

exit(0);

__END__

Here is a run through:


$ perl readfiles.pl rhyme.txt
################# beginning of rhyme.txt ################
Mary had a little lamb,
It was always bleating.

################# end of rhyme.txt ################

[/example]

[reference]

[tags], Perl Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

Your email address will not be published. Required fields are marked *