Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

slice

perl

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);
like image 970
NXT Avatar asked May 09 '10 23:05

NXT


2 Answers

lib->import(join('/', splice(@{[split('/', $bin)]}, 0, -4)).'/lib');
like image 163
pdehaan Avatar answered Sep 30 '22 19:09

pdehaan


Check the splice function.

like image 27
Igor Krivokon Avatar answered Sep 30 '22 17:09

Igor Krivokon