How to organize private methods for Perl objects?

What is the correct way to handle methods that will not be called by the user? For example, if the user calls a method, say do_stuff()from a script driver, and if do_stuff()relies on other routines, it is best to name these submasters from the method do_stuff()as follows:

sub do_stuff {
    my ( $self, %arg ) = @_;
    #does it things
    #and then calls the private sub as follows
    _private_sub( $self, %arg );
}
+4
source share
4 answers

If your method do_stuffneeds the functionality that you decide to keep "private", then you must invoke _private_subinside it. This is his goal. Of course, the presence of sub be "private" is conditional, since it cannot be applied.

coderefs private subs

my $_private = sub { ... };  # must be at least predeclared

sub do_stuff {
    my ($self, %arg) = @_;
    # ...
    my $from_private = $self->$_private->(@args);    # or
    my $more_private = $_private->($self, @args);
}

, , , , . , mob, .

$_private , , , . . (, , ), - .

, .

, "private" , . , . , .

Moose Moo - .

+3

, "" . Perl , , - . , , , , .

EDIT: . "caller()" , -, . , , - , .

+4

$self->_private_sub(...)? , $obj->_method , , .

, , , - ?

sub do_stuff {
    my ( $self, %arg ) = @_;
    ...
    _private_sub( %arg, $self );
}

sub _private_sub {
    my $self = pop;
    my %args = @_;
    ...
}
+1

, , , . - Perl 5.18 . . perldoc perlsub.

: . Perl.

use feature 'lexical_subs', , "experimental: lexical_subs" .

Perl 5.18, my state. , use feature 'state' use 5.010 .

These routines are visible only inside the block in which they are declared, and only after this declaration:

no warnings "experimental::lexical_subs";
use feature 'lexical_subs'; 

foo();              # calls the package/global subroutine

state sub foo {
  foo();            # also calls the package subroutine
}

foo();              # calls "state" sub
my $ref = \&foo;    # take a reference to "state" sub

my sub bar { ... }
bar();              # calls "my" sub

To use the lexical subprogram inside the subprogram itself, you must provide it. The subroutine definition syntax sub foo {...}matches any previous declaration my sub;or state sub;.

my sub baz;         # predeclaration
sub baz {           # define the "my" sub
  baz();            # recursive call
}
+1
source

Source: https://habr.com/ru/post/1666054/


All Articles