matt
matt

Reputation: 243

Printing perl struct members

I have a struct and would like to print out the contents within quotes

#!/usr/bin/perl

use Class::Struct;

struct( astruct => [ test => '$']);

my $blah = new astruct;
$blah->test("asdf");

print "prints array reference: '$blah->test'\n";
print "prints content: '", $blah->test, "'\n";

The output is

prints array reference: 'astruct=ARRAY(0x20033af0)->test'
prints content: 'asdf'

Is there a way to print the contents within the quotes?

Its making my code a bit scruffy having to open and close quotes all the time. It's also problematic when using `` to run commands which use the contents of structs.

Upvotes: 0

Views: 2301

Answers (2)

amon
amon

Reputation: 57640

The variable $blah holds an array reference and is interpolated into the string before it can be dereferenced. To change that, we put the dereferencing either outside the String:

print "prints no array reference any more: '".($blah->test)."'\n";
# parenthesis was optional

or pull a little trick with an anonymous array:

print "prints no array reference any more: '@{[$blah->test]}'\n";

We dereference (@{...}) an anonymous array ([...]) which we construct from the return value of the test method. (Our your struct field, whatever.)

While both these methods work when constructing a string, the second form can easily be used in a qx or backticks environment. You could also build a string $command and then execute that with qx($command).

If you don't need the additional functionality of the Class::Struct, you can always use hashes and spare yourself the hassle:

%blah = (test => 'asdf');
print "prints my value: '$blah{test}'\n";

or

$blah = {test => 'asdf'};
print "prints my value: '$blah->{test}'\n";

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272307

Have you considered Perls' Data::Dumper ?

Given a list of scalars or reference variables, writes out their contents in perl syntax. The references can also be objects. The content of each variable is output in a single Perl statement. Handles self-referential structures correctly.

Upvotes: 2

Related Questions