Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of <> in Perl?

Tags:

perl

What's the use of <> in Perl. How to use it ? If we simply write

<>; 

and

while(<>) 

what is that the program doing in both cases?

like image 312
bubble Avatar asked Sep 05 '12 06:09

bubble


People also ask

What is -> symbol in Perl?

The arrow operator ( -> ) is an infix operator that dereferences a variable or a method from an object or a class. The operator has associativity that runs from left to right. This means that the operation is executed from left to right.

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.

How do you negate in Perl?

Unary "!" performs logical negation, that is, "not". Languages, what have boolean types (what can have only two "values") is OK: if it is not the one value -> must be the another one. But perl doesn't have boolean variables - have only a truth system , whrere everything is not 0 , '0' undef , '' is TRUE.


1 Answers

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.

like image 146
Tony K. Avatar answered Sep 28 '22 00:09

Tony K.