http://qs1969.pair.com?node_id=1156424

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:

use My::Module; My::Module::print_file_name();
and ./lib/My/Module.pm:
package My::Module; use feature qw(say); sub print_file_name { say __FILE__; } 1;
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):
if ( !File::Spec->file_name_is_absolute( $filename ) ) { $filename = File::Spec->rel2abs( $filename, $FindBin::Bin ); }
but the problem is that $filename is not relative to $FindBin::Bin so it will not work.

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: