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

Printing an Hash

by anshumangoyal (Scribe)
on Aug 01, 2012 at 14:26 UTC ( [id://984801]=perlquestion: print w/replies, xml ) Need Help??

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

I have a hash which has around 20 Key Value Pairs. I want to print these values in a file and on screen in such a way that the indentation is not lost. I want to print it in mysql query output format. The Keys will be name of parameter and below it the value of the key has to be printed. I tried with sprintf but it's not a success. The keys length are different and so it he value length. What is the best possible solution?

Replies are listed 'Best First'.
Re: Printing an Hash
by BillKSmith (Monsignor) on Aug 01, 2012 at 16:01 UTC
      or Data::Printer (my fave because you have to type less, you get fancy colors, and indices are included in the output)
Re: Printing an Hash
by blue_cowdawg (Monsignor) on Aug 01, 2012 at 17:57 UTC

    printf "%s\n", join("\n",map { $_ . " " . $hash{$_} } sort keys %hash);


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Printing an Hash
by suaveant (Parson) on Aug 01, 2012 at 14:53 UTC
    Why don't you type up an example of how you want the data to look, that'd help a lot in pointing you to a solution.

                    - Ant
                    - Some of my best work - (1 2 3)

Re: Printing an Hash
by Rudolf (Pilgrim) on Aug 01, 2012 at 15:37 UTC

    This should keep all of your indentation, though Im not aware of how you want it printed out, so I just put each key and value on a newline

    use v5.14; my %hash = (' key' => 'value ',"\tkey2" => "value2\t"); open(FILE,'>>','filename') or die "$!"; while ( my($key, $value ) = each(%hash)){ print "$key\n$value\n"; print FILE "$key\n$value\n"; } close FILE;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-20 09:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found