Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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?

Replies are listed 'Best First'.
Re: Printing an Hash
by BillKSmith (Priest) 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 rifling through the Monastery: (8)
As of 2016-07-29 17:37 GMT
Find Nodes?
    Voting Booth?
    What is your favorite alternate name for a (specific) keyboard key?

    Results (264 votes). Check out past polls.