Perl Tips and Tricks

Read entire contents of a file to string.

Option 1:

my $text=””;

open (FILE,”<file.txt”) or die “Can’t open file”;

while(<FILE>) { $text .= $_; };

Option 2:

my $text=””;

open (FILE,”<file.txt”) or die “Can’t open file”;

my @lines = <FILE>; for (@lines) { $text.= $_; }

Option 3: Works only in unix

my $text = `cat file.txt`;

Write to STDIN of unix command

open (CMD,”| cat << EOF”) or die “Can’t execute command”;

print CMD “text\n”;

print CMD “EOF\n”;

close (CMD);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s