in reply to Re^5: Append JSON (from hashref)
in thread Append JSON (from hashref)

Can you give some advice on preping this in perl, so far my attempt is failing to produce a structure required:
while (my $row = $sth->fetchrow_hashref) { print "doc_no: $row->{RECNO} DESCRIPTION: $row->{DESCRIPTION}\n"; $hash{$int} = '"RECNO": "' . $row->{RECNO} . '","DESCRIPTION": "' . +$row->{DESCRIPTION} .'"'; $int ++; } # figure out how to add inputPhrase later.
Is there a structure I can use which means I don't have to have the $int part?

Replies are listed 'Best First'.
Re^7: Append JSON (from hashref)
by Corion (Patriarch) on Apr 07, 2017 at 06:12 UTC

    If you want to numerically index something, use an array, not a hash.

    See perldsc on Perl Data Structures, and maybe Modern Perl about a good book on Perl in general.

Re^7: Append JSON (from hashref)
by huck (Prior) on Apr 06, 2017 at 15:51 UTC

    There is something you are not telling us, your example link shows a hash as the containing structure, yet your example json is a hash inside an array. Is this what you want?

    my $tmp = $dbh->selectall_arrayref($query, { Slice => {} }, $SearchWor +d ); my $container={items=>$tmp->[0]}; $container->{inputPhrase}=$SearchWord; my $json_str = encode_json( $container );
    Just what is it you expect to see returned?

      changing one line of your code to
      my $container={items=>$tmp};
      worked, providing the structure needed. Thanks
Re^7: Append JSON (from hashref)
by AnomalousMonk (Archbishop) on Apr 06, 2017 at 19:41 UTC

    This is tangential to the main theme of this thread, but a statement like
        $hash{$int} = '"RECNO": "' . $row->{RECNO} . '","DESCRIPTION": "' . $row->{DESCRIPTION} .'"';
    can be written in what I consider a much more readable way as, e.g.,
        $hash{$int} = qq{"RECNO": "$row->{RECNO}","DESCRIPTION": "$row->{DESCRIPTION}"};
    using the  qq{} generic double-quotish (i.e., interpolating) string constructor (see Quote and Quote-like Operators in perlop). Note that bracketing delimiters handle balanced nested bracketing delimiters of the same type, so something like
        $hash{$int} = qq{{... whatever ...}};
    works as you expect.


    Give a man a fish:  <%-{-{-{-<