develooper Front page | perl.perl5.porters | Postings from March 2016

[perl #127646] Option to avoid __FILE__ variable containing relativepath

Thread Next
From:
Håkon Hægland
Date:
March 2, 2016 19:30
Subject:
[perl #127646] Option to avoid __FILE__ variable containing relativepath
Message ID:
rt-4.0.18-2815-1456947034-760.127646-75-0@perl.org
# New Ticket Created by  Håkon Hægland 
# Please include the string:  [perl #127646]
# in the subject line of all future correspondence about this issue. 
# <URL: https://rt.perl.org/Ticket/Display.html?id=127646 >


I am writing a module that implements a subroutine that requires to
read the source file of the caller. The filename of the caller can be
obtained from the Perl caller() function, but unfortunately it is
sometimes a relative pathname, which is not relative to the current
directory, but to what *was* the current directory when the file was
loaded. That current directory may very well have changed at the time
my module inspects the variable, and hence it is no longer possible to
recover the absolute pathname of the file.

I believe the caller() function gets the filename from package
variable "__FILE__".

I suspect the reason that __FILE__ is not populated with an absolute
path in these cases, is to avoid the call to Cwd::getcwd() when the
module is loaded. Maybe it was/is considered that this call would be
to expensive and not worth the cost?

If this is the case, would it be possible to introduce an environment
variable, for example PERL5FILEPATH, that if set to "absolute" would
force a call to Cwd::getcwd() and to populate __FILE__ with an
absolute path at the time a module is loaded?

On the other hand, if the variable PERL5FILEPATH is not set, or set to
"relative", things work as today. This is the default behavior and
Cwd::getcwd() is not called.

This should also work for the main program file "$0", and it could
eliminate the use of "$FindBin::Bin".

Why use an environment variable like PERL5FILEPATH? Why not a special
variable like $^FILE_PATH? The reason is that the variable must be set
very early at compile time in order for it to have effect. Most
modules are loaded with "use" or "require" at compile time in BEGIN {}
blocks. Since it is not possible to inject code to be executed before
all BEGIN {} blocks this approach seems not viable.

When does __FILE__ become relative? For modules, it will become
relative if @INC contains a relative path name, like './lib',
'./test', or simply the current directory '.'.

Of course if the cost of Cwd::getcwd() is not the reason why __FILE__
can be relative, other measures might be required.

Best regards,
Håkon Hægland


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About