Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Code asks, in what file do I live?

by water (Deacon)
on Sep 23, 2004 at 17:44 UTC ( [id://393282]=perlquestion: print w/replies, xml ) Need Help??

water has asked for the wisdom of the Perl Monks concerning the following question:

How can a snippet of running code determine which file it came from (assuming it wasn't built on the fly)? I know $0 gives you the program, and __PACKAGE__ gives you the package, but how does one get to the filename?

Thanks!

water

Replies are listed 'Best First'.
Re: Code asks, in what file do I live?
by Sidhekin (Priest) on Sep 23, 2004 at 17:51 UTC

    Is __FILE__ what you are looking for?

    sidhekin@blackbox:~$ perl -le 'print __FILE__' -e sidhekin@blackbox:~$

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re: Code asks, in what file do I live?
by shemp (Deacon) on Sep 23, 2004 at 17:53 UTC
    use caller().
    ($packeage, $filename, $line) = caller;
    Called without an arguement, caller() returns the above, about the currently executing subroutine.
      Called without an arguement, caller() returns the above, about the currently executing subroutine.
      Er, actually it returns stuff about the caller of the current subroutine.

      Dave.

        Er, actually it returns stuff about the caller of the current subroutine

        Well, if you pass in 0 (caller(0)) then you get the caller information for the current stack frame plus some more information.

        my $filename = (caller(0))[1];
          A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Code asks, in what file do I live?
by ikegami (Patriarch) on Sep 23, 2004 at 17:46 UTC

    Maybe you want this:

    package Foo::Bar; sub test { my $pkg = __PACKAGE__; $pkg =~ s#::#/#g; $pkg .= '.pm'; print($INC{$pkg}, "\n"); }

    It definitely has limitations (when package Foo::Bar isn't in or only in Foo/Bar.pm, for starters.

    On second thought, caller provides some nice info:

    package Pkg; sub test { local $,=", "; local $\="\n"; print(caller(0)); } test(); __END__ output ====== Pkg, script.pl, 10, Pkg::test, 1, , , , 0,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://393282]
Approved by TStanley
Front-paged by mhi
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-25 14:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found