Stephen
Stephen

Reputation: 8878

Can we get a stack trace for strict refs violations in Perl?

I am using use strict in my Perl program, but the errors aren't as helpful as they could be since they just list the single offending line. Is there a way to get backtraces when use strict fails?

Upvotes: 1

Views: 54

Answers (1)

amon
amon

Reputation: 57656

The strict pragma contains the categories subs which forbids barewords, and vars which requires you to declare all variables. Those are compile-time errors. A stack trace for these is not helpful, as they directly stem from the source code on that line.

The strict category refs forbids strings as references, which is a runtime error. Here a stacktrace may be helpful to figure out where that string came from.

One way to get a stack trace is to use Carp::Always (or as a command line flag: -MCarp::Always). This modifies all errors and warnings to include a stack trace. Because it makes all errors much longer, is best to only use this as a debugging help.

If you're having the problem that your subroutines are getting invalid arguments, it may be better to validate the inputs. E.g.:

use Carp;

sub foo {
  my ($ref) = @_;

  # dies from the line where "foo()" was called
  croak q(Argument "ref" must be a scalar reference)
    unless ref $ref eq 'SCALAR' or ref $ref eq 'REF';

  do_something_with($$ref);
}

When using one of the functions from Carp (e.g. croak() or confess()) you can force a stack trace by adding the Perl option -MCarp=verbose.

Upvotes: 6

Related Questions