How do I refer to a scalar in a hash reference in Perl?

Simple question:

How to do it in one line:

my $foo = $bar->{baz};
fizz(\$foo);

      

I've tried \ $ bar -> {baz}, \ $ {$ bar -> {baz}} and many others. Is it possible?

-fREW

Update : Ok, the hashref comes from the DBI and I am passing the scalar link to the templating toolbox. I think now that I look more closely, the problem has to do with how TT does it all. I want to say:

$template->process(\$row->{body}, $data);

      

But TT doesn't work, TT takes a scalar ref and puts the data in there, so I would have to do this:

$template->process(\$row->{body}, $shopdata, \$row->{data});

      

Anyway, thanks for the help. I will have at least one link instead of two.

0


source to share


4 answers


\$bar->{baz}

      

must work.

eg:.

my $foo;
$foo->{bar} = 123;

my $bar = \$foo->{bar};

$$bar = 456;

print "$foo->{bar}\n";   # prints "456"

      



In response to an update in the OP, you can do:

\@$row{qw(body data)};

      

This is not the same as \ @array, which will create a single reference to the array. The above will distribute the link and make a list of two links.

+5


source


\ $ bar -> {baz} seems to do the trick for me:



my $bar = { baz => 1 };
print $bar->{baz}, "\n";  # prints 1
my $ref =  \$bar->{baz};
print $$ref, "\n";        # prints 1
$$ref = 2;
print $bar->{baz}, "\n";  # prints 2 

      

+4


source


You didn't show how% bar and fizz () were set, so I set them like this:

my %hash;
my $bar = \%hash;
$hash{baz} = "found it\n";
sub fizz {
  my $ref = shift;
  print $$ref;
}

      

Then both of these work, your orignal:

my $foo = $bar->{baz};
fizz(\$foo);

      

and one of the options you said you tried:

fizz(\$bar->{baz});

      

Can you show the error that is giving you?

+2


source


I'm not even sure what you are doing. You should also put quotes around baz.

Now consider that you are assigning a scalar to a scalar on the first line, then the second line should work. However, I don't know if this is really what you are trying here and it doesn't make much sense in Perl. The use of links is often used in other languages ​​to

  • speed up the function call
  • allow you to return multiple values.

Now the former is generally not needed with scalars, and Perl is a script language anyway, so if you are really concerned about the writing speed of C.

The second is not needed in Perl, as you can easily and easily add lists and references to anonymous hashes.

Have you looked at "perlref man"?

0


source







All Articles