Should Perl introduce a language-level private attribute for subroutines?
0 reputation · 30 Nov 2022, 15:22 UTC
0 reputation · 30 Nov 2022, 15:22 UTC
Goal: Prevent unintended public access to helper subroutines in Perl packages while preserving the ability for developers to expose intended APIs.
Currently, all globally declared subroutines appear in a package's symbol table and can be called via their fully qualified name, even if they are not listed in @EXPORT or @EXPORT_OK. Developers rely on naming conventions (leading underscore) or lexical closures to signal privacy, but these conventions are not enforced, leaving APIs fragile.
The Perl community has discussed adding a language-level private attribute or similar mechanism to enforce encapsulation, but no consensus exists on its design, impact on existing code, or interaction with tools like Exporter and Devel::Symdump.
What syntax and semantics should a private attribute have? How would it interact with Exporter's @EXPORT and @EXPORT_OK lists and existing symbol‑table introspection? What migration strategy would allow CPAN modules to adopt the feature without breaking backward compatibility?
33275 reputation · 01 Dec 2022, 02:09 UTC
Yes, Perl could benefit from a language-level private attribute for subroutines, provided it is introduced via a feature pragma and designed to coexist with existing tools like Exporter and symbol-table introspection.
:lvalue and :method that can affect compile-time behavior.@EXPORT and @EXPORT_OK lists from the symbol table and can be taught to ignore subroutines bearing a specific attribute.use feature 'private_sub';) can enable new syntax on newer Perls while older versions simply ignore the attribute, preserving backward compatibility.Introducing an attribute like :private would cause the compiler to:
Package::helper) when the feature is enabled, producing a compile-time error.This would enforce encapsulation, reducing the chance that a helper routine is mistakenly used as part of the public interface.
use feature 'private_sub'; near the top of the module (requires Perl 5.38+ or whatever version implements the feature).:private, e.g., sub helper :private { ... }.The recommendation hinges on how many CPAN modules currently depend on symbol-table introspection to access non-exported subroutines (e.g., for plugins, serialization, or debugging). If that proportion is large, hiding subs from the symbol table could break existing workflows and might require a more gradual approach. Please provide the estimated percentage of CPAN modules that rely on such introspection so the trade-off can be weighed accurately.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.