Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Format values into a hash question

by Anonymous Monk
on Mar 05, 2013 at 16:50 UTC ( #1021869=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am trying to format the data in the hash "$row" before pushing it to @query_output, I am not sure if I am doing the right way. Is there a better way of doing this?
Here is a sample of what I am trying:
... my @query_output;my $new_row=(); while ( my $row = $data_handle->fetchrow_hashref ){ #push @query_output, $row; $new_row = "First:", $row->{'NAME_ONE'}, " Last: ", $row->{'NAME_TW +O'}, " CITY: " , $row->{'CITY'}, "ZIP:" ,$row->{'ZIP'}; push @query_output, $new_row; } ...
Thanks for looking!

Comment on Format values into a hash question
Download Code
Re: Format values into a hash question
by roboticus (Canon) on Mar 05, 2013 at 17:36 UTC

    No, I'd suggest you change line 7 to:

    $new_row = "First: $row->{'NAME_ONE'} Last: $row->{'NAME_TWO'} CITY: $ +row->{'CITY'} ZIP: $row->{'ZIP'}";

    The problem is that you're creating a set of values, and sticking only one into $new_row, and discarding the rest. If you'd print the contents of $new_row afterwards, you'll see it.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Format values into a hash question
by aitap (Deacon) on Mar 05, 2013 at 17:47 UTC
    The comma (,) constructs a list which is not what you want (as long as $new_row is just a string scalar). Interpolate your variables inside your quoted string, as suggested above, or use the dot (.) to join strings: push @query_output, "First:" . $row->{'NAME_ONE'} . " Last: " . $row->{'NAME_TWO'} . " CITY: " . $row->{'CITY'} . "ZIP:" . $row->{'ZIP'};
    Sorry if my advice was wrong.
Re: Format values into a hash question
by 7stud (Deacon) on Mar 06, 2013 at 07:52 UTC

    Next up is this:

    my $new_row=();

    What does that do?

    use strict; use warnings; use 5.016; my $new_row = (); if (defined $new_row) { say 'yes'; } else { say 'no'; } --output:-- no

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1021869]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2014-11-23 05:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (128 votes), past polls