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:

In reply to How to determine absolute path of current Perl file? by hakonhagland

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.