Perl映射块局部变量的使用
此代码通过一组路径中唯一基本名称存根的哈希键来编译一组。
%stubs = map { $f=basename $_; $f =~ /^([A-Za-z]+[0-9]+)\./ ; $1=>() } @pathlist;
为什么这里需要 $f
引用?我以为我可以接受:
%stubs = map { basename; /^([A-Za-z]+[0-9]+)\./; $1=>() } @pathlist;
但我没有匹配到。我是否不允许修改地图块中的 $_ ?
对于那些想知道代码在做什么的人:
对于每个 $path (@pathlist),它获取基本名称,匹配第一个字母数字序列,然后返回第一个括号匹配作为空列表值上的键。示例:
/some/dir/foo123.adfjijoijb
/some/dir/foo123.oibhobihe
/some/dir/bar789.popjpoj
返回
foo123 => ()
bar789 => ()
之后,我使用映射的键作为值集进行处理。
This code compiles a set by way of hash keys of the unique basename stubs in a set of paths.
%stubs = map { $f=basename $_; $f =~ /^([A-Za-z]+[0-9]+)\./ ; $1=>() } @pathlist;
Why do I need the $f
references here? I thought I'd be ok with:
%stubs = map { basename; /^([A-Za-z]+[0-9]+)\./; $1=>() } @pathlist;
But I get no match. Am I not permitted to modify $_ in the map block?
For those wondering what the code is doing:
For each $path (@pathlist), it's getting the basename, matching the first letter-number sequence, and then returning the first bracket match as the key on an empty list value. Example:
/some/dir/foo123.adfjijoijb
/some/dir/foo123.oibhobihe
/some/dir/bar789.popjpoj
returns
foo123 => ()
bar789 => ()
After which I use the keys of the map as the set of values so process.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
basename 并不默认作用于
$_
。但是您可以匹配它的返回值,而不是使用 $f:请注意,列表中的 () 不会生成元素,它只是扁平化为空;你必须提供一个值,即使只是undef。与
$1 => ()
,映射迭代将交替为 %stubs 生成一个键和一个值。在使用 $1 之前总是检查你的正则表达式是否成功是很好的:
尽管如果你不介意哈希值是空字符串而不是 undef,你可以让正则表达式匹配返回所需的列表:
basename does not default to acting on
$_
. But you can match against its return value instead of using $f:Note that () in a list doesn't produce an element, it just flattens to nothing; you have to provide a value, even if only undef. With
$1 => ()
, map iterations would alternate producing a key and a value for %stubs.It's good to always check that your regex succeed before using $1:
though if you don't mind the hash values being the empty string instead of undef, you can just make the regex match return the desired list:
在map和grep中,$_是数组中值的别名。如果修改它们,实际上就是修改数组中的值。这可能不是您想要的,也可能不是出了问题,但是在这两种情况下都要调试打印键 %stubs 和 @pathlist 并让我们知道它说的是什么。
另外:File::Basename 的基本名称不能隐式地作用于 $_。它为我生成一个错误。
In map and grep, $_ is an alias for the values in the array. If you modify them, you actually modify the values in the array. This is probably not what you want and probably what is going wrong, but to debug print keys %stubs and @pathlist afterwards in both cases and let us know what it says.
Also: File::Basename's basename does not implicitly work on $_. It generates an error for me.
替代实施:
Alternate implementation: