Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Printing an Hash

by anshumangoyal (Scribe)
on Aug 01, 2012 at 14:26 UTC ( #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?

Comment on Printing an Hash
Replies are listed 'Best First'.
Re: Printing an Hash
by BillKSmith (Curate) 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?

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2015-11-26 00:27 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (693 votes), past polls