问题
I have got an array @address whose zero element contains some strings.
I can not find an example diamond operator works with @array as argument.
(how it 'split' strings?)
use Mojo::Loader qw/ data_section /;
my @address = data_section 'main', 'address_strings';
while( my $line = <@address> ) {
print $line;
}
1;
__DATA__
@@ address_strings
"010101, УУУ обл., м. Тернопіль, вул. ВВВ, буд. 0101, 01"
"020202, ЛЛЛ обл., ААА район, село ФФФ, ВУЛИЦЯ ШШШ, будинок 01"
"030303, м.ЮЮЮ, ЮЮЮ р-н, вул. ЛЛЛ, буд.01, офіс 01"
UPD
Reading from doc <> operator allow GLOB or filehandle, but in my case that is just array of one string.
my @arr = <<TEXT;
many
lines
TEXT
while( my $line = <@arr> ) {
print ">>$line<<\n";
}
Does <> do something magic for this case? You can notice, that lines are splitted
回答1:
That's ... not what the diamond operator does, which is why you can't find any examples.
You only need:
foreach my $line ( @address ) {
print $line;
}
The <> denotes reading from a file handle, and @address is not a file handle. It isn't even an array of file handles.
You could theoretically do
while ( my $line = <DATA> ) {
print $line;
}
Which because DATA is a file handle, <> triggers a single record read from that filehandle. (record boundary defaults to linefeed, but you can change $/)
This wouldn't make sense given what you're doing with Mojo, I merely give it as an example of how it should work.
回答2:
<> is potentially two different operators, glob or readline. If what is in it is a simple scalar variable or a bareword, it is a readline operation, and the argument is the filehandle to use. Otherwise, it is a glob operation and the argument is treated as whitespace separated filenames (or filename wildcards to expand).
When <> is a glob operation, it is treated as a double-quotish context, and arrays are interpolated by joining with $" (which defaults to space). So <@x> is glob "@x" is glob join $", @x. So assuming $" is unchanged and there are no wildcards in the elements of @x, it is very much like just split ' ', "@x", joining all the elements together with spaces and then splitting the results on whitespace.
回答3:
Have a look at perldoc -f glob.
A typical usage would be:
my @suffix = qw(*.yaml *.json);
my @yaml = <@suffix>;
# or directly
my @yamlfiles = <*.yaml *.json>;
So be careful when using it for data that could potentially be a filename wildcard ;-)
来源:https://stackoverflow.com/questions/63905986/how-does-diamond-operator-work-with-array-as-argument