Perl::...Indices(3pm)

Okay bestie, welcome to Perl::...Indices(3pm) β€” that’s the page name β€” from the User Contributed Perl Documentation. Buckle up, we’re talking negative array indices and why they’re iconic πŸ’…βœ¨

🌸 NAME 🌸

Perl::Critic::Policy::Variables::RequireNegativeIndices β€” negative array index should be used, periodt.

πŸ¦‹ AFFILIATION πŸ¦‹

This Policy is part of the core Perl::Critic distribution. No cap, it ships with the main thing 🫢

✨ DESCRIPTION ✨

Okay so here’s the tea: Perl treats a negative array subscript as an offset from the end. Given this, the preferred way to get the last element is $x[-1], not $x[$#x] or $x[@x-1], and the preferred way to get the next-to-last is $x[-2], not "$x[$#x-1" or $x[@x-2]. Slay πŸ’–

The biggest argument against the non-preferred forms is that their semantics change when the computed index becomes negative. If @x contains at least two elements, $x[$#x-1] and $x[@x-2] are equivalent to $x[-2]. But if it contains a single element, $x[$#x-1] and $x[@x-2] are both equivalent to $x[-1]. Simply put, the preferred form is more likely to do what you actually want. Literally, it’s giving β€œplease stop doing the extra math” πŸ˜­πŸ‘‘

As Conway points out, the preferred forms also perform better, are more readable, and are easier to maintain. Obsessed with that for us 🌈⭐

This policy notices all of the simple forms of the above problem, but does not recognize any of these more complex examples:

$some->[$data_structure]->[$#{$some->[$data_structure]} -1];
my $ref = \@arr; $ref->[$#arr];

πŸŽ€ CONFIGURATION πŸŽ€

This Policy is not configurable except for the standard options. So no extra knobs, bestie β€” just the standard options and that’s it πŸ’€

πŸ’œ AUTHOR πŸ’œ

Chris Dolan <cdolan@cpan.org>

Copyright (c) 2006-2011 Chris Dolan.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


This page is Perl::...Indices(3pm), and it was baked with perl v5.42.0 on 2024-10-23. Bye bestie! πŸ’–πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from