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

Hello Monks,

I've been searching for a solution to dump the contents of an entire hashref (HoH) - returned from a dbi fetchall_hashref into a scalar (not a $hashref).

Best attempt I could come up with is this:

my $param = join(q{, }, map{qq{$_ => $$ref2{$_}}} keys %$ref2);


but it's returning:

4 => HASH(0x5755668), 3 => HASH(0x55ddbb8), 2 => HASH(0x574e670), 9 => + HASH(0x5767a18), 11 => HASH(0x5527fd8), 1 => HASH(0x574f230), 8 => H +ASH(0x5639d48), 6 => HASH(0x574c6c8), 7 => HASH(0x54fae40), 12 => HAS +H(0x5747fc8), 5 => HASH(0x562be30), 13 => HASH(0x57633d0), 10 => HASH +(0x57648f8)


Or is it possible to use data::dumper to put contents into a scalar? As always, thanks for helping me to figure this out!
- 3dbc

Replies are listed 'Best First'.
Re: DBI fetchall_hashref convert to scalar
by stevieb (Canon) on Feb 03, 2017 at 00:11 UTC

    Because a hash reference is already a scalar, I'm assuming that you mean you want it into a scalar *string*. Here's one way that you can exploit a scalar reference to be used as a memory file, and write the output of Data::Dumper directly to that scalar as a string value.

    use warnings; use strict; use Data::Dumper; my $href = { a => 1, b => [ 2, 3, ], c => { 25 => 'y', 26 => 'z', }, d => 4, }; my $memfile; open my $mfh, '>', \$memfile or die $!; print $mfh Dumper($href); close $mfh; print $memfile;

    Output:

    $VAR1 = { 'c' => { '25' => 'y', '26' => 'z' }, 'b' => [ 2, 3 ], 'd' => 4, 'a' => 1 };

      Does the use of $memfile as a memory file actually buy you anything, stevieb? I can't see how what you have there differs from the simpler alternative:

      use warnings; use strict; use Data::Dumper; my $href = { a => 1, b => [ 2, 3, ], c => { 25 => 'y', 26 => 'z', }, d => 4, }; my $text = Dumper ($href); print $text;

      What am I missing?

      in using this method you might find this helpfull
      local $Data::Dumper::Indent=0;

        Hey huck,

        If you're recommending that switch, could you please show us an example of it in use (ie. what happens when it's used), and let us know the purpose of using that var?

Re: DBI fetchall_hashref convert to scalar
by kcott (Archbishop) on Feb 03, 2017 at 01:48 UTC

    G'day 3dbc,

    I'd take a look at the built-in module Storable.

    It's DESCRIPTION starts:

    "The Storable package brings persistence to your Perl data structures containing SCALAR, ARRAY, HASH or REF objects, ..."

    And, right after that, the MEMORY STORE section begins:

    "The Storable engine can also store data into a Perl scalar instead, to later retrieve them. ..."

    — Ken

Re: DBI fetchall_hashref convert to scalar
by huck (Prior) on Feb 03, 2017 at 00:03 UTC

    my $param = join(q{, }, map{qq{$_ => $ref2->{$_}}} keys %$ref2);
    ok, so i dont get how the => ends up as text? Nevermind qq