new_perl
new_perl

Reputation: 7755

Need more explanation about what's being done here?

print reverse <>;
print sort <>;

What's the exact steps perl handles with these operations?

It seems for the 1st one,perl not just reverses the order of invocation parameters,but also the contents of each file...

Upvotes: 1

Views: 70

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234857

This is described in the docs for I/O operators. Here's an excerpt from the docs:

The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames.

It's worth reading the entire doc, as it provides equivalent "non-magical" Perl code equivalent to <> in various use cases.

Upvotes: 1

Seth Robertson
Seth Robertson

Reputation: 31471

 print reverse <>;

<> is evaluated in an array context, meaning it "slurps" the file. It reads the entire file. In the case of the magic file represented by the files named in @ARGV, it will read the contents of all files in the order referenced by the command line arguments (@ARGV).

reverse then reverses the order of the array, meaning the last line from the last file comes first, and the first line from the last file comes last.

print then prints the array.

From your notes, you might want something like this:

perl -e 'sub BEGIN { @ARGV=reverse @ARGV; } print <>;' /etc/motd /etc/passwd

Upvotes: 2

Related Questions