How can I print the contents of a hash in Perl?

前端 未结 11 1541
借酒劲吻你
借酒劲吻你 2020-12-22 15:52

I keep printing my hash as # of buckets / # allocated. How do I print the contents of my hash?

Without using a while loop would be most preferable (for

11条回答
  •  情深已故
    2020-12-22 16:19

    For debugging purposes I will often use YAML.

    use strict;
    use warnings;
    
    use YAML;
    
    my %variable = ('abc' => 123, 'def' => [4,5,6]);
    
    print "# %variable\n", Dump \%variable;
    

    Results in:

    # %variable
    ---
    abc: 123
    def:
      - 4
      - 5
      - 6
    

    Other times I will use Data::Dump. You don't need to set as many variables to get it to output it in a nice format than you do for Data::Dumper.

    use Data::Dump = 'dump';
    
    print dump(\%variable), "\n";
    
    { abc => 123, def => [4, 5, 6] }
    

    More recently I have been using Data::Printer for debugging.

    use Data::Printer;
    p %variable;
    
    {
        abc   123,
        def   [
            [0] 4,
            [1] 5,
            [2] 6
        ]
    }
    

    ( Result can be much more colorful on a terminal )

    Unlike the other examples I have shown here, this one is designed explicitly to be for display purposes only. Which shows up more easily if you dump out the structure of a tied variable or that of an object.

    use strict;
    use warnings;
    
    use MTie::Hash;
    use Data::Printer;
    
    my $h = tie my %h, "Tie::StdHash";
    @h{'a'..'d'}='A'..'D';
    p %h;
    print "\n";
    p $h;
    
    {
        a   "A",
        b   "B",
        c   "C",
        d   "D"
    } (tied to Tie::StdHash)
    
    Tie::StdHash  {
        public methods (9) : CLEAR, DELETE, EXISTS, FETCH, FIRSTKEY, NEXTKEY, SCALAR, STORE, TIEHASH
        private methods (0)
        internals: {
            a   "A",
            b   "B",
            c   "C",
            d   "D"
        }
    }
    

提交回复
热议问题