0

I want to have a Perl script that receives a file and do some computation based on it.

Here is my try:

Perl.pl

#!/usr/bin/perl

use strict;
use warnings;

my $book = <STDIN>;

print $book;

Here is my execution of the script:

./Perl.pl < textFile

My script only prints the first line of textFile. Who can I load all textFile into my variable $book?

I want the file to be passed in that way, I do not want to use Perl's open(...)

4

3 回答 3

4

Assigning a value from a file handle to a scalar pulls it one line at a time.

You can either:

  • use a while loop to append the lines one by one until there are none left or
  • set $/ (to undef) to change your script's idea of what constitutes a line. There is an example of the latter in perldoc perlvar (read it as it explains best practises for changing it).
于 2013-03-30T20:48:14.727 回答
1

Also you can use Path::Class for easy. It is a wrapper for many file manipulation modules.

For your purpose:

#! /usr/bin/perl
use Path::Class qw/file/;

my $file = file(shift @ARGV);
print $file->slurp;

You can run it by:

./slurp.pl textFile
于 2013-03-31T02:07:29.793 回答
0

The answer you're looking for is in the Perl FAQ.

How can I read in an entire file all at once?

于 2013-03-31T03:41:27.910 回答