Perl - 如何获取匿名数组中的元素数量,以简洁地修剪路径名
我正在尝试将一段代码缩减为一行。我需要一种方法来获取列表中的项目数。我的代码目前看起来像这样:
# Include the lib directory several levels up from this directory
my @ary = split('/', $Bin);
my @ary = @ary[0 .. $#ary-4];
my $res = join '/',@ary;
lib->import($res.'/lib');
太棒了,但我想把这一行写成这样:
lib->import( join('/', ((split('/', $Bin)) [0 .. $#ary-4])) );
但是当然,语法 $#ary
在上面的行中是没有意义的。
是否有等效的方法来获取匿名列表中的元素数量?
谢谢!
PS:合并此内容的原因是它将位于a的标题中 一堆附属于主应用程序的 perl 脚本,我想要这个 小咒语要更切&粘贴证明。
谢谢大家
匿名中的元素数量似乎没有简写 列表。这似乎是一个疏忽。然而,建议的替代方案都很好。
我同意:
lib->import(join('/', splice( @{[split('/', $Bin)]}, 0, -4)).'/lib');
但是 Ether 建议了以下内容,这是更正确和可移植的:
my $lib = File::Spec->catfile(
realpath(File::Spec->catfile($FindBin::Bin, ('..') x 4)),
'lib');
lib->import($lib);
I'm trying to get a block of code down to one line. I need a way to get the number of items in a list. My code currently looks like this:
# Include the lib directory several levels up from this directory
my @ary = split('/', $Bin);
my @ary = @ary[0 .. $#ary-4];
my $res = join '/',@ary;
lib->import($res.'/lib');
That's great but I'd like to make that one line, something like this:
lib->import( join('/', ((split('/', $Bin)) [0 .. $#ary-4])) );
But of course the syntax $#ary
is meaningless in the above line.
Is there equivalent way to get the number of elements in an anonymous list?
Thanks!
PS: The reason for consolidating this is that it will be in the header of a
bunch of perl scripts that are ancillary to the main application, and I want this
little incantation to be more cut & paste proof.
Thanks everyone
There doesn't seem to be a shorthand for the number of elements in an anonymous
list. That seems like an oversight. However the suggested alternatives were all good.
I'm going with:
lib->import(join('/', splice( @{[split('/', $Bin)]}, 0, -4)).'/lib');
But Ether suggested the following, which is much more correct and portable:
my $lib = File::Spec->catfile(
realpath(File::Spec->catfile($FindBin::Bin, ('..') x 4)),
'lib');
lib->import($lib);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查 splice 函数。
Check the splice function.
您可以使用 splice 函数操作数组(例如删除最后 n 个元素) ,但您也可以使用负索引生成数组的切片(其中 -1 表示最后一个元素,-2 表示倒数第二个元素,等等):例如
@list = @arr[0 .. -4 ]
是合法的。但是,当您似乎想要的是 lib 目录的位置时,您似乎要经历很多后空翻操作这些列表。向 perl 可执行文件提供 -I 参数,或者使用 $FindBin::Bin< 不是更容易吗? /a> 和 File::Spec->catfile 定位相对目录到脚本的位置?
You can manipulate an array (such as removing the last n elements) with the splice function, but you can also generate a slice of an array using a negative index (where -1 means the last element, -2 means the second to last, etc): e.g.
@list = @arr[0 .. -4]
is legal.However, you seem to be going through a lot of backflips manipulating these lists when what you seem to be wanting is the location of a lib directory. Would it not be easier to supply a -I argument to the perl executable, or use $FindBin::Bin and File::Spec->catfile to locate a directory relative to the script's location?