开发者

Perl - How to get the number of elements in an anonymous array, for concisely trimming pathnames

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 leve开发者_如何学编程ls 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);


lib->import(join('/', splice(@{[split('/', $bin)]}, 0, -4)).'/lib');


Check the splice function.


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?

use strict;
use warnings;

use Cwd 'realpath';
use File::Spec;
use FindBin;

# get current bin
# go 4 dirs up,
# canonicalize it,
# add /lib to the end
# and then "use" it

my $lib = File::Spec->catfile(
                realpath(File::Spec->catfile($FindBin::Bin, ('..') x 4)),
               'lib');
lib->import($lib);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜