Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

aliasing a hash field

by Sixtease (Friar)
on Feb 15, 2008 at 16:41 UTC ( [id://668176]=perlquestion: print w/replies, xml ) Need Help??

Sixtease has asked for the wisdom of the Perl Monks concerning the following question:

Dear fellows

Can I alias a hash entry to a global variable? I'd like something like this to happen:

our @arr; my %h; somehow_alias($h{'key'}, @arr); $h{'key'}[0,1] = qw(hello world); print $arr[0], ' ', $arr[1], "\n"; # Desired output: # hello world

Now that's the Y part. The X part is that I'm running user-provided subrefs in a module and would like these subs to see some fields that the $self object has without messing with the sub's parameters.

use strict; use warnings; print "Just Another Perl Hacker\n";

Replies are listed 'Best First'.
Re: aliasing a hash field
by BrowserUk (Patriarch) on Feb 15, 2008 at 18:06 UTC
Re: aliasing a hash field
by kyle (Abbot) on Feb 15, 2008 at 16:58 UTC

    I don't see a way for $h{'key'}[0,1] to be valid syntax regardless. Maybe this is close enough?

    use Test::More 'no_plan'; our @arr; my %h; $h{'key'} = \@arr; # take a reference to @arr @{$h{'key'}}[0,1] = qw(hello world); is( $arr[0], 'hello', '$arr[0] is "hello"' ); is( $arr[1], 'world', '$arr[1] is "world"' ); is( $h{'key'}->[0], 'hello', q{$h{'key'}->[0] is 'hello'} );
Re: aliasing a hash field
by Sixtease (Friar) on Feb 15, 2008 at 20:24 UTC

    Yeah, ehm, well, I must have been high on something when I wrote that. :-)

    *arr = $h{'key'} is the obvious solution to Y that should have crossed my mind.

    $h{'key'}[0,1] may not be invalid syntax but it's definitely not what I meant.

    The solution to X is that I simply make a method to set the things I want to show to the subs instead of adding magic to manipulating the object.

    My question was totally unclear and I apologize. Seeing that I got helpful and not bashing replies confirms my deep conviction that the Perlmonks community is one of the most mature, tolerant and wonderful communities to ever inhabit the cyberspace.

    use strict; use warnings; print "Just Another Perl Hacker\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://668176]
Approved by kyle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2024-03-28 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found