tags:

views:

73

answers:

1

How do I find out the name of a file that was require'd, from within that file? I can look into %INC to find the names of all files that were loaded, but I am looking for something like $0 that would serve as the key into %INC.

+7  A: 

a simple

my $filename=__FILE__;
print __FILE__;

should do ..

also look here (does-a-perl-module-know-where-it-is-installed) and here ( perldoc on Special-Literals ) for more ideas

lexu
Thanks, that was it. Bizarrely, you can't do $INC{__FILE__} because that looks up $INC{'__FILE__'}, so you need to go through an intermediate variable.
Peter Eisentraut
Peter: That's not entirely unexpected. $foo{bar} autoquotes, too. __FILE__ looks like any other identifier. Similar issues apply to constants.
tsee
@Peter Eisentraut: If you need to use `__FILE__` in a hash, use this `$INC{''.__FILE__}`. A little bit more typing, but it gets you there. All you need is one non-word char.
Axeman
@tsee: Yeah but with constants, you can just throw `()` at the end to get them to evaluate: `MY_CONSTANT_PI()` (not in a string, though).
Axeman
@Axeman: That's just for `use constant` style constants, which some people don't really like...
ephemient
the perlish way of defeating bareword autoquoting is with the unary plus operator: `$INC{+__FILE__}` works.
hobbs
@hobbs: I'mma gonna go gouge my eyes out now. *That's* inobvious code.
Paul Nathan