开发者

How can I get name of an object in Perl?

Say I make an object as follows:

$object22=new somepackage("stuff");

and later I want to run a subroutine like this:

$object22->somesubroutine();

I would like to capture the string "object22" in the sub开发者_如何学编程routine "somesubroutine." I tried:

$self=@_;
print $self;

but that just gave me somepackage=HASH(somehexnumber)

Please let me know if this is possible and if so what the code is to do so.


This is impossible without horrible hackery (looking through the stack frames). The name is just a reference to the object, it is not part of the object.

You're approaching the problem in the wrong way. Perhaps describe it more?


I can think of two ways to get around your problem:

  1. make the name you're interested in a attribute of the object
  2. store your objects in a hash, using the name as the key

Paul


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.


This is possible with horrible hackery that crawls through the stack frames. Something like PadWalker, perhaps.

But you're probably approaching the problem wrong.


Call 'blessed': https://metacpan.org/pod/Scalar::Util#blessed.

It is also exported automatically if you are using moose.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜