hakonhagland has asked for the wisdom of the Perl Monks concerning the following question:
Background:
I am trying to improve the CPAN module Data::Printer such that it can display the variable name automatically (similarly to Data::Dumper::Simple). However, I will try to do this without using PadWalker or a source filter ( perlfilter or Filter::Util::Call ). Instead, I will try read the source file by exploiting filename and line number of current source from caller. Then parsing the line with PPI to recover the variable name.
Problem
My current problem is to determine the absolute path of the current Perl file. The problem occurs when the filename (as given by (caller)[1] ) is relative. For example running perl ./test/test.pl with ./test/test.pl:
and ./lib/My/Module.pm:use My::Module; My::Module::print_file_name();
will give output lib/My/Module.pm (the same will perl function caller) which is a relative path name. My first attempt was to use FindBin (since I cannot rely on the current directory being the same as when the script was run):package My::Module; use feature qw(say); sub print_file_name { say __FILE__; } 1;
but the problem is that $filename is not relative to $FindBin::Bin so it will not work.if ( !File::Spec->file_name_is_absolute( $filename ) ) { $filename = File::Spec->rel2abs( $filename, $FindBin::Bin ); }
Then I considered using Module::Path, but this seemed like overkill for my use case. What I think I need is a simple module, say Cwd::Initial which gives me the initial working directory. For example:
package Cwd::Initial; use strict; use warnings; use Cwd (); our $cwd; our $VERSION = '0.10'; sub _getcwd { $cwd = Cwd::getcwd(); } BEGIN { _getcwd(); } sub getcwd { return $cwd; } 1;
Questions
Some questions:- Have I missed something? Is this functionality already available at CPAN?
- If not, is the module Cwd::Initial really necessary? Should I instead suggest a modification to FindBin to expose the initial directory as part of its API?
- Or, is the use case so special that I should rather not rely on a CPAN module to provide this but instead use a BEGIN{} block and a package variable our $inital_cwd?