Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of the <*> symbol

Tags:

io

perl

perldoc

I've recently been exposed to a bit of Perl code, and some aspects of it are still elusive to me. This is it:

@collection = <*>;

I understand that the at-symbol defines collection as an array. I've also searched around a bit, and landed on perldoc, specifically at the part about I/O Operators. I found the null filelhandle specifically interesting; code follows.

while (<>) {
    ...
}

On the same topic I have also noticed that this syntax is also valid:

while (<*.c>) {
    ...
}

According to perldoc It is actually calling an internal function that invokes glob in a manner similar as the following code:

open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
while (<FOO>) {
    ...
}

Question

What does the less-than, asterisk, more-than (<*>) symbol mentioned on the first line actually do? Is it a reference to an internally open and referenced glob? Would it be a special case, such as the null filehandle? Or can it be something entirely different, like a legacy implementation?

like image 412
OnoSendai Avatar asked Dec 02 '25 21:12

OnoSendai


2 Answers

<> (the diamond operator) is used in two different syntaxes.

<*.c>, <*> etc. is shorthand for the glob built-in function. So <*> returns a list of all files and directories in the current directory. (Except those beginning with a dot; use <* .*> for that).

<$fh> is shorthand for calling readline($fh). If no filehandle is specified (<>) the magical *ARGV handle is assumed, which is a list of files specified as command line arguments, or standard input if none are provided. As you mention, the perldoc covers both in detail.

How does Perl distinguish the two? It checks if the thing inside <> is either a bare filehandle or a simple scalar reference to a filehandle (e.g. $fh). Otherwise, it calls glob() instead. This even applies to stuff like <$hash{$key}> or <$x > - it will be interpreted as a call to glob(). If you read the perldoc a bit further on, this is explained - and it's recommended that you use glob() explicitly if you're putting a variable inside <> to avoid these problems.

like image 66
rjh Avatar answered Dec 05 '25 14:12

rjh


It collects all filenames in the current directory and save them to the array collection. Except those beginning with a dot. It's the same as:

@collection = glob "*";
like image 29
edi_allen Avatar answered Dec 05 '25 14:12

edi_allen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!