An alternative to using the stack frames is using caller ()
to get the line your routine was called from and then read the program file and get the variable name like that.
#!/usr/local/bin/perl
use warnings;
use strict;
package X;
sub new
{
bless {};
}
sub getdownonthatcrazything
{
my ($self) = @_;
my (undef, $file, $line) = caller ();
open my $in, "<", $file or die $!;
while (<$in>) {
if ($. == $line) {
goto found;
}
}
die "Something bad happened";
found:
if (/\$(\w+)\s*->\s*getdownonthatcrazything\s*\(\)/) {
my $variable = $1;
print "I was called by a variable called \$$variable.\n";
}
close $in or die $!;
}
1;
package main;
my $x = X::new ();
$x->getdownonthatcrazything ();
my $yareyousofunky = X::new ();
$yareyousofunky->getdownonthatcrazything ();
Output:
$ ./getmycaller.pl
I was called by a variable called $x.
I was called by a variable called $yareyousofunky.
This assumes that your files are all in the same directory. If not you could use the FindBin module and search @INC
for libraries, etc.