Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the source location of a print statement in Perl?

Tags:

perl

How can I find the source location of a print statement in Perl?

#!/usr/bin/perl

foo();
bar();

sub foo {
  print "foo\n";
}

sub bar {
  print "bar\n";
}

The output being:

>perl test.pl 
foo
bar

I'd like to somehow find be able to see (or something like)

>perl test.pl 
main::foo> foo
main::bar> bar

The reason for this is I'm trying to track down some rouge output, and cannot find its location in a large code base.

like image 936
Matthew Watson Avatar asked May 25 '09 00:05

Matthew Watson


2 Answers

Try this:

#!/usr/bin/env perl

use strict;
use warnings;
use Tie::STDOUT print => sub {
  my ( $pkg, $file, $line ) = caller(2);
  print "$pkg, $file, $line :: ", @_;
};

print "Hello, World\n";

Which gives:

$ perl tp.pl
main, tp.pl, 10 :: Hello, World

Update: I've just released Devel::Ditto:

$ perl -MDevel::Ditto myprog.pl
[main, t/myprog.pl, 9] This is regular text
[main, t/myprog.pl, 10] This is a warning
[MyPrinter, t/lib/MyPrinter.pm, 7] Hello, World
[MyPrinter, t/lib/MyPrinter.pm, 8] Whappen?
like image 121
hexten Avatar answered Oct 23 '22 03:10

hexten


Use Debug::Trace ( https://metacpan.org/pod/Debug::Trace )

#!/usr/bin/perl

foo();
bar();

sub foo {
  print "foo\n";
}

sub bar {
  print "bar\n";
}

This program, saved as test.pl and called as:

perl -MDebug::Trace=foo,bar test.pl

Prints out:

TRACE:  main::foo() called at test.pl line 3 package main
foo
TRACE:  main::foo() returned
TRACE:  main::bar() called at test.pl line 4 package main
bar
TRACE:  main::bar() returned
like image 34
rpkelly Avatar answered Oct 23 '22 02:10

rpkelly