Perl - How to get the number of elements in an anonymous array, for short cropping paths

I am trying to get a block of code up to one line. I need a way to get the number of items in a list. Currently my code is as follows:

# 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'); 

This is great, but I want to make one line, something like this:

 lib->import( join('/', ((split('/', $Bin)) [0 .. $#ary-4])) ); 

But of course, the syntax of $#ary does not make sense in the line above.

Is there an equivalent way to get the number of items in an anonymous list?

Thanks!

PS: The reason for the consolidation is that it will be in the header of a bunch of perl scripts that are auxiliary to the main application, and I want this little spell to be more cut and pasted.

Thanks everyone

There seems to be no reduction in the number of items in the anonymous list. This is like surveillance. However, the proposed alternatives were good.

I'm going to:

 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); 
+6
arrays perl slice
source share
3 answers
 lib->import(join('/', splice(@{[split('/', $bin)]}, 0, -4)).'/lib'); 
+3
source share

Check out splice .

+2
source share

You can manipulate the array (for example, delete the last n elements) using the splice function, but you can also generate a slice of the array using a negative index (where -1 means the last element, -2 means the second is the last, etc.) : for example @list = @arr[0 .. -4] is legal.

However , it looks like you are looking at a lot of reverse folk manipulating these lists when what you think is right is the location of the lib directory. Wouldn't it be easier to provide the -I argument to the perl executable or use $ FindBin :: Bin and File :: Spec-> catfile to find the directory relative to the location of the script?

 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); 
+1
source share

All Articles