What’s the use of in Perl?

The answers above are all correct, but it might come across more plainly if you understand general UNIX command line usage. It is very common to want a command to work on multiple files. E.g.

ls -l *.c

The command line shell (bash et al) turns this into:

ls -l a.c b.c c.c ...

in other words, ls never see ‘*.c’ unless the pattern doesn’t match. Try this at a command prompt (not perl):

echo *

you’ll notice that you do not get an *.

So, if the shell is handing you a bunch of file names, and you’d like to go through each one’s data in turn, perl’s <> operator gives you a nice way of doing that…it puts the next line of the next file (or stdin if no files are named) into $_ (the default scalar).

Here is a poor man’s grep:

while(<>) {
   print if m/pattern/;
}

Running this script:

./t.pl *

would print out all of the lines of all of the files that match the given pattern.

cat /etc/passwd | ./t.pl

would use cat to generate some lines of text that would then be checked for the pattern by the loop in perl.

So you see, while(<>) gets you a very standard UNIX command line behavior…process all of the files I give you, or process the thing I piped to you.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)