Can the Perl compiler tell me if I have an exception in my code?

Is there a way in Perl to declare that a method may cause an error (or die)?

The EDIT: . What interests me the most is this way of getting the compiler or IDE to tell me that I have an exception to my code.

I always liked how, in Java, a method can handle an exception and / or throw it. The signature of the method allows you to place a "throws MyException", so a good IDE / compiler would know that if you use the specified method somewhere in your code, you will need to check the Exception or declare that your function "throws" the Exception further.

I can not find something similar to Perl. My colleague wrote a method that "dies" when it is entered incorrectly, but I forgot eval-if ($ @) that ... in the end, the error was detected only when the application started.

(offcourse I doubt if there is any existing IDE that could find such things for Perl, but at least perl -cw should be able to, no?)

+3
source share
4 answers

Two potential answers. Choose what you like best:

  • In Perl, this is indicated by the POD module. There is no way to label it programmatically, so you only need to rely on the documentation.

  • die , , . - , , , - .., , , - () , , , t20 > . , .

:. , Perl5 . , Perl6, .

+3

, , , ?

, Attribute::Handlers

ThrowsExceptionHandler.pm

package ThrowsExceptionHandler;
use Modern::Perl;
use Attribute::Handlers;

our @subs;

sub ThrowsException :ATTR(CODE) {
    push @subs, {
        package  => $_[0],
        symbol   => $_[1],
        subname  => *{$_[1]}{NAME},
        referent => $_[2],
        attr     => $_[3],
        data     => $_[4],
        phase    => $_[5],
        filename => $_[6],
        linenum  => $_[7],
    };
}

sub does_throw {
    my ($class, $subname) = @_;
    (grep { $_->{subname} eq $subname } @subs) ? 1 : 0;
}

1;

example.pl

use Modern::Perl;
use base qw(ThrowsExceptionHandler);

sub baz :ThrowsException {
    die "Throws error";
}

sub foo {
    warn "warning only";
}


say ThrowsExceptionHandler->does_throw( 'baz' );  # => 1
say ThrowsExceptionHandler->does_throw( 'foo' );  # => 0

() PPI, Perl::Critic / Padre , - ?

/I3az/

+2

" Exceptions"

  • $@ , .

  • :

    sub throw { my $mess = join ('', @_); $ mess = ~ s/\n? $/\n/; my $i = 1; local $"=" ',' "; DB; while (my @parts = caller ($ ++)) { $q; $q = "'" @DB:: args; $ mess. = "- > $parts3". "at $parts 1 line $parts 2\"; } $mess; }

CPAN" " - Perl"

-3

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


All Articles