How can I get the name of an object in Perl?

Let's say I create an object as follows:

$object22=new somepackage("stuff");

and then I want to run the routine as follows:

$object22->somesubroutine();

I would like to write the string "object22" in the routine "somesubroutine". I tried:

$self=@_;
print $self;

but it just gave me somepackage=HASH(somehexnumber)

Please let me know if this is possible, and if so, which code will do it.

-1
source share
5 answers

This is not possible without a terrible hacker (viewing stack frames). A name is just a reference to an object; it is not part of the object.

You are approaching the problem wrong. Maybe describe it more?

+7
source

I can come up with two ways to get around your problem:

  • ,
  • ,

+2

, . - PadWalker, .

, , .

+1

caller (), , , .

#!/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 ();

:

$ ./getmycaller.pl 
I was called by a variable called $x.
I was called by a variable called $yareyousofunky.

, . , FindBin @INC ..

+1

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

It is also exported automatically if you use a moose.

0
source

Source: https://habr.com/ru/post/1762556/


All Articles