What does reading from <> do in Perl? For example, what will the following do?
print for(<>);
The so-called diamond operator (<>) reads line-by-line (in scalar context) from STDIN or the filename(s) specified as command-line arguments.
From perldoc perlop:
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@ARGVarray is checked, and if it is empty,$ARGV[0]is set to"-", which when opened gives you standard input. The@ARGVarray is then processed as a list of filenames.
In list context, <> returns all lines, with each line stored as an element in the list.
This means that print for <>; will do the same thing as print while <>;, albeit with more memory.
You've found the single most magical piece of Perl. Well, I'm sure there's more magical things, but this little idiom makes it very easy to write programs intended for shell pipeline use and file-operation use.
When run without any arguments, <> will read lines one-at-a-time from standard input.
When run with arguments, it'll treat the arguments as filenames and read lines one-at-a-time from the named files in turn.
A short demo:
$ cat > print.pl
#!/usr/bin/perl -w
print for(<>);
$ chmod 755 print.pl
$ echo hello world | ./print.pl
hello world
$ ./print.pl print.pl
#!/usr/bin/perl -w
print for(<>);
$ ./print.pl print.pl print.pl
#!/usr/bin/perl -w
print for(<>);
#!/usr/bin/perl -w
print for(<>);
$
I typed in the program by hand there; hit ^D when you've typed it in completely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With