[sf-perl] Perl references to arrays vs. references to shared arrays
David Christensen
dpchrist at holgerdanske.com
Thu Aug 13 18:05:47 PDT 2020
On 2020-08-11 16:55, David Christensen wrote:
> I have been working with nested data structures.
> To detect circular loops ... stringify a reference
> But the technique fails for data structures built from shared variables.
The solution is to use shared::threads::is_shared:
https://metacpan.org/pod/threads::shared
In the example below, I used Scalar::Util::refaddr for consistency:
2020-08-13 18:00:18 dpchrist at tinkywinky ~/sandbox/perl
$ cat circular-arrayref-vs-shared-arrayref.pl
#!perl
use strict;
use warnings;
use threads;
use threads::shared;
use Scalar::Util qw( refaddr );
my @a0;
my @a1;
my @sa0 :shared;
my @sa1 :shared;
sub d {
no warnings 'uninitialized';
printf "%i %s=[%21s] %s=[%21s]\n",
(caller)[2],
refaddr(\@a0), refaddr($a0[0]),
refaddr(\@a1), refaddr($a1[0]);
}
sub e {
no warnings 'uninitialized';
printf "%i %s=[%21s] %s=[%21s]\n",
(caller)[2],
is_shared(@sa0), is_shared($sa0[0]),
is_shared(@sa1), is_shared($sa1[0]);
}
print "\nArrays with circular references:\n";
d; d; d;
$a0[0] = \@a1; d; d; d;
$a1[0] = \@a0; d; d; d;
print "\nShared arrays with circular references:\n";
e; e; e;
$sa0[0] = \@sa1; e; e; e;
$sa1[0] = \@sa0; e; e; e;
2020-08-13 18:00:22 dpchrist at tinkywinky ~/sandbox/perl
$ perl circular-arrayref-vs-shared-arrayref.pl
Arrays with circular references:
33 93884874649056=[ ] 93884874649128=[
]
33 93884874649056=[ ] 93884874649128=[
]
33 93884874649056=[ ] 93884874649128=[
]
34 93884874649056=[ 93884874649128] 93884874649128=[
]
34 93884874649056=[ 93884874649128] 93884874649128=[
]
34 93884874649056=[ 93884874649128] 93884874649128=[
]
35 93884874649056=[ 93884874649128] 93884874649128=[
93884874649056]
35 93884874649056=[ 93884874649128] 93884874649128=[
93884874649056]
35 93884874649056=[ 93884874649128] 93884874649128=[
93884874649056]
Shared arrays with circular references:
38 93884875574272=[ ] 93884875574296=[
]
38 93884875574272=[ ] 93884875574296=[
]
38 93884875574272=[ ] 93884875574296=[
]
39 93884875574272=[ 93884875574296] 93884875574296=[
]
39 93884875574272=[ 93884875574296] 93884875574296=[
]
39 93884875574272=[ 93884875574296] 93884875574296=[
]
40 93884875574272=[ 93884875574296] 93884875574296=[
93884875574272]
40 93884875574272=[ 93884875574296] 93884875574296=[
93884875574272]
40 93884875574272=[ 93884875574296] 93884875574296=[
93884875574272]
David
More information about the SanFrancisco-pm
mailing list