简体   繁体   中英

How do I return a string as a one element array reference in Perl?

I'm new to Perl, and this thing has got me stuck for far too long...

I want to dump a readable representation of the object itself from inside a function (I'm trying to debug something, and I'm doing this by returning an array reference which the caller expects, but containing an object dump rather than human readable text as per normal) so in my package I have:

use Data::Dumper;

sub somefunctionName{

my $self = shift;
my $d = Dumper($self);
my @retval = ();
push(@retval, $d);
return \@retval;
}

This is giving me the error "Can't use string ("the literal object dump goes here") as a HASH ref while "strict refs" in use"

I can't for the life of me figure out a way to make the error go away, no matter how I mess with the backslashes, and what I've done above looks to me like exactly what every online tutorial does... But I'm obviously missing the point somewhere.

What am I doing wrong?

According to the documentation

  • Dumper(LIST)

    Returns the stringified form of the values in the list, subject to the configuration options below. The values will be named $VAR n in the output, where n is a numeric suffix. Will return a list of strings in a list context.

You should be able to do

@retval = Dumper($self);
return \@retval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM