How to create a self-referring datastructure in one line

J

jdamon

Hi,

I'm trying to create a self referential datastructure in one line.


An example is :



my %tree;
%tree = (
root => {
parent1 => {
child => {
data => "foo",
root => $tree{root} # or even \%{$tree{root}}
}
}
}
);

The problem is that the reference doesn't exist at the time that the
structure is created.

If you are going to post back to this , I DON'T want the solution when
you build this up iteratively. I just want to know if it can be done
in a declaration like stated above.
 
M

Mark Clements

Hi,

I'm trying to create a self referential datastructure in one line.
Why?
An example is :



my %tree;
%tree = (
root => {
parent1 => {
child => {
data => "foo",
root => $tree{root} # or even \%{$tree{root}}
}
}
}
);

The problem is that the reference doesn't exist at the time that the
structure is created.

use strict; use warnings; my $var; $var = \$var; print "$var ${$var}\n";


Or am I missing the point?
 
M

Mirco Wahab

$_->{root} = {
parent => {
child => {
data => 'foo',
root => \$$_{root}
}
}
} for \my %tree;

I can't imagine why a one-liner requirement is necessary, however.

Interesting Idea. That one leads directly to the
'one expression initialization' (what I think was meant):

...

my %tree = (
map {
$_->{root} = {

parent => {
child => {
data => 'foo',
root => \$$_{root}
}
}

};
%$_
} {}
);

...

Thanks for this nice idea (didn't know
"this way" of post instantiation-
initialization of hashes)

Regards

M.
 
A

anno4000

Hi,

I'm trying to create a self referential datastructure in one line.


An example is :



my %tree;
%tree = (
root => {
parent1 => {
child => {
data => "foo",
root => $tree{root} # or even \%{$tree{root}}
}
}
}
);

The problem is that the reference doesn't exist at the time that the
structure is created.

If you are going to post back to this , I DON'T want the solution when
you build this up iteratively. I just want to know if it can be done
in a declaration like stated above.

How absolutely charming.

Build the data structure you want in the way you have forbidden to post
about. Then use Data::Dumper on it to see how to rebuild it in a
single statement.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top