Read Lines From File

+4 Gregory Ballantine · April 30, 2014
Hey guys!

Here's a somewhat-short little Perl script that will read the lines from a file and print them out.

use strict;
use warnings;

my $file = ""; # Declare $file globally
if ($ARGV[0]) { # If there is a script argument
$file = $ARGV[0]; # Set $file to the argument value
} else { # Else if there's no argument
$file = "test.txt"; # Set $file to test.txt
}

# Create the array
my @lines = do {
unless (open FILE, "<", $file) { # If this fails...
die "Could not open the file $file: $!"; # Terminate script and print the error
}
<FILE>
};

foreach (@lines) { # Loop through the array
printf "%s", $_; # Print out the current line
}


Or if you have File::Slurp installed:

use strict;
use warnings;
use File::Slurp; # Import the Slurp module

my $file = ""; # Declare $file globally
if ($ARGV[0]) { # If there is a script argument
$file = $ARGV[0]; # Set $file to the argument value
} else { # Else if there's no argument
$file = "test.txt"; # Set $file to test.txt
}

# Create the array
my @lines = read_lines($file);

foreach (@lines) { # Loop through the array
printf "%s", $_; # Print out the current line
}


As with many other things with programming (or scripting, if you prefer to call it), there are many other ways to do this, these are just a couple of the ways I've used ^.^. By no means are these the only!

Any critiques are welcome!

Post a Reply

Replies

Oldest  Newest  Rating
0 William Frost · July 19, 2014
Nice job mate! :)
0 Nathan Lile · January 13, 2015
Nice dude! Thanks for the contribution. It would be nice to have more PERL on here.
  • 1

Perl

107,273 followers
About

Used for graphics, system administration, network programming, finance, and other applications.

Links
Moderators
Bucky Roberts Administrator