Perl: convert string to link?

Possible duplicate:
How to convert a gated version of an array reference to an array reference in Perl?

I have "SCALAR (0x8ec3a94)" as a literal string. Can I get Perl to turn this into a link and then follow it?

IE, tell Perl: "look at memory location 0x8ec3a94 and process what is there as a scalar"?

Related: Perl: Smallest list expansion not working?

And yes, I understand that this is terrible.

+8
coding-style perl
source share
2 answers

Closest you can get Tie :: RefHash . Poor person's version contains hash links

$registry{"$ref"} = $ref; 

and then pull it out later

 print ${ $registry{"SCALAR(0x8ec3a94)"} }, "\n"; 

This approach has many disadvantages. Why do you want to do it this way?

+3
source share

From the link provided by Andy, try the Inline::C approach . You will want to use SV* rather than AV* , but it should work.

I mocked the example by extending the method shown in this link. With my limited knowledge of C, I think I prevented Segfault when the link no longer points to anything (test without commenting on the curly braces, allowing text to be excluded from the volume). Since I use newRV_inc in section C, the reference count for $text incremented. Therefore, if $text falls out of scope, but the found link ( $recovered_ref ) still exists, the value is still available, as expected (test, without commenting on external curly braces).

This method seems to work for any type of link. Not sure about the objects, let them go if you want. For more information, perldoc Inline::C will help, but you will need to read perldoc perlguts and possibly even perldoc perlapi to continue this path.

 #!/usr/bin/perl use strict; use warnings; use Inline 'C'; my $stringified_ref_text; my $stringified_ref_array; my $recovered_ref_text; my $recovered_ref_array; #{ #{ my $text = "Hello World"; my @array = qw"Hello World!"; $stringified_ref_text = \$text . ""; $stringified_ref_array = \@array . ""; print $stringified_ref_text . "\n"; print $stringified_ref_array . "\n"; #} $recovered_ref_text = recover_ref($stringified_ref_text); $recovered_ref_array = recover_ref($stringified_ref_array); #} print $$recovered_ref_text . "\n"; print "$_\n" for @$recovered_ref_array; sub recover_ref { my $input = shift; my $addr; if ($input =~ /0x(\w+)/) { $addr = hex($1); } else { warn "Could not find an address"; return undef; } my $ref = _recover_ref($addr) or undef; return $ref; } __DATA__ __C__ SV* _recover_ref(int address) { if (address) return newRV_inc((SV*) address); return 0; } 
+3
source share

All Articles