在perl中,有没有一种简洁的方法来组合glob和printf?
我希望 @list 包含 $root_dir 中与 *YYYYMMDD* 匹配的所有文件名,其中 YYYYMMDD 是 25 小时前。
我尝试……
my ($y, $m, $d) = (localtime(time - 25 * 60 * 60))[5,4,3];
my $pattern = sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d);
print "The pattern is $pattern\n";
my @files = <$pattern>;
foreach (@files) {
print "$_\n";
}
但我没有获取文件列表,而是在未打开的文件句柄上获取了 readline() 。
我知道<>运算符可以解释变量,因此 <$y$m$d>可以在一年最后三个月的三分之二的日子里工作,因为这些月份和日期都是两位数,但这并不可靠。
我必须写……
$m = sprintf('%02d',$m+1);
$d = sprintf('%02d',$d+1);
my @files = <*$y$m$d*>;
还是有更简洁的东西?像...
# invalid code unless you want to produce the string "readline() on unopened filehandle" for some reason
my @files = <sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d)>;
I want @list to contain all the filenames in $root_dir that match *YYYYMMDD*, where YYYYMMDD is 25 hours ago.
I try ...
my ($y, $m, $d) = (localtime(time - 25 * 60 * 60))[5,4,3];
my $pattern = sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d);
print "The pattern is $pattern\n";
my @files = <$pattern>;
foreach (@files) {
print "$_\n";
}
... but instead of getting a list of files, I get readline() on unopened filehandle.
I know the <> operator can interpret variables, so <$y$m$d> would work during two-thirds of the days during the last three months of the year because those would be months and days that have two digits, but that is not robust.
Do I have to write ...
$m = sprintf('%02d',$m+1);
$d = sprintf('%02d',$d+1);
my @files = <*$y$m$d*>;
... or is there something more concise? Something like ...
# invalid code unless you want to produce the string "readline() on unopened filehandle" for some reason
my @files = <sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d)>;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
<...>
运算符已经太重载了。具体来说,<$...>
被视为文件句柄。Use
The
<...>
operator is way too overloaded already. Specifically,<$...>
is taken as a filehandle.<>
可以表示readline
或glob
,具体取决于它的使用方式。来自珀洛普:由于
$pattern
是一个简单的标量,因此它被解释为作为句柄,Perl 尝试执行readline
。直接调用glob
:<>
的重载可能会有点混乱。如果您认为这是一种有趣的编写iterator->next
的方式,这可能会有所帮助。 (readline
和glob
都像标量上下文中的迭代器一样。)<>
can mean eitherreadline
orglob
depending on how it's used. From perlop:Since
$pattern
is a simple scalar it is interpreted as a handle and Perl attempts to do areadline
. Callglob
directly instead:The overloading of
<>
can be a little confusing. It might help if you think of it as being a funny way of writingiterator->next
. (Bothreadline
andglob
act like iterators in scalar context.)有点多余,你可以使用 CPAN 中的东西来代替所有这些恶作剧:
A bit superfluous, instead of all those shenanigans, you could use something from CPAN instead: