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
.
views:
73answers:
1
+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
2010-01-07 11:52:39
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
2010-01-07 12:16:39
Peter: That's not entirely unexpected. $foo{bar} autoquotes, too. __FILE__ looks like any other identifier. Similar issues apply to constants.
tsee
2010-01-07 15:23:15
@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
2010-01-07 21:45:19
@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
2010-01-07 21:46:45
@Axeman: That's just for `use constant` style constants, which some people don't really like...
ephemient
2010-01-07 22:06:46
the perlish way of defeating bareword autoquoting is with the unary plus operator: `$INC{+__FILE__}` works.
hobbs
2010-01-08 23:30:23
@hobbs: I'mma gonna go gouge my eyes out now. *That's* inobvious code.
Paul Nathan
2010-01-21 17:08:20