Perl "Closing" Using Hash

I would like to have a subroutine as a member of a hash that can have access to other hash members.

for instance

sub setup {
  %a = (
   txt => "hello world",
   print_hello => sub {
    print ${txt};
  })
return %a
}

my %obj = setup();
$obj{print_hello};

Ideally, it displays "hello world"

EDIT

Sorry, I could not specify one requirement.

I must be able to do

$obj{txt} = "goodbye";

and then $ obj {print_hello} should output goodbye

+3
source share
3 answers

If you want the calling code to be able to modify the message in the hash, you need to return the hash by reference. This does what you requested:

use strict;
use warnings;

sub self_expressing_hash {
    my %h;
    %h = (
        msg              => "hello",
        express_yourself => sub { print $h{msg}, "\n" },
    );
    return \%h;
}

my $h = self_expressing_hash();
$h->{express_yourself}->();

$h->{msg} = 'goodbye';
$h->{express_yourself}->();

However, this is a bizarre mix - essentially a data structure that contains some built-in behavior. Sounds like an object to me. Perhaps you should explore the OO approach for your project.

+7

:

sub setup { 
    my %a = ( txt => "hello world" );
    $a{print_hello} = sub { print $a{txt} };
    return %a;
}

my %obj = setup();
$obj{print_hello}->();
+2

sub setup {
  my %a = (
   txt => "hello world",
   print_hello => sub {
    print $a{txt};
  });
  return %a;
}

my %obj = setup();
$obj{print_hello}->();
0

Source: https://habr.com/ru/post/1750119/


All Articles