in reply to Re: Print Data::Dumper with format
in thread Print Data::Dumper with format

Hi, I want to print all contacts that i add to the hash. But it has to be with that header. For example, if i have 3 contacts:
================================================ Name LastName Email Address Phone ================================================ John Matt J_m@gmail Park av. 465512 Math Perry ..... .... .... Julie .... ..... .... .....
I hope you understand now... I use Data::Dumper to print all... Thanks for everything!

Replies are listed 'Best First'.
Re^3: Print Data::Dumper with format
by Loops (Curate) on Oct 20, 2014 at 03:55 UTC

    Okay, that makes sense. So there are few things that need to change in your code. As you've already figured out, Data::Dumper isn't the tool you want to use to create tables. A good choice for that instead is Text::Table. This module will automatically adjust column sizes for you to accommodate whatever text is entered for each field.

    Also, you want your code to accept multiple contact entries, looping once for each person entered. After each entry you create a hash for that person(as your code already does), and accumulate the hashes in an array. This array will hold multiple hashes, one for each person entered

    Once the last person has been entered you can use Text::Table to print out this array of hashes.

    #!/usr/bin/perl use strict; use warnings; use diagnostics; use Data::Dumper; use Text::Table; # Chomp each input to remove trailing linefeed immediately sub entrada{ my ($var) = shift; print "Ingrese $var: "; my $in = <STDIN>; chomp $in; return $in; } # Return a reference to the hash that holds all of the contact informa +tion sub contact_entry { my @contact =(); my $name = entrada('Name'); my $lastName = entrada('Last Name'); my $address = entrada('Address'); my $email = entrada('Email'); my $phone = entrada('Phone Number'); my $image = entrada('Image Profile'); my $detailProfile = entrada('Detail Profile'); my %contact_entry = ( name => $name, lastName => $lastName, address => $address, email => $email, phone => $phone, image => $image, detailProfile => $detailProfile ); return \%contact_entry; } # Create a hash for each contact entered, and add it to the end of our + array my @contacts; while (1) { my $contact = contact_entry; push @contacts, $contact; print "Desea ingresar mas Contactos?[S/n]:"; my $input = <STDIN>; chomp($input); last if $input ne 's'; } # Set the header my $table = Text::Table->new( "Nombre\n======", "Apellido\n========", "E-mail\n======", "Direccion\n=========", "Telefono\n========" ); # load the data into the table, converting each hash to an array with +only the proper columns $table->load( map { [ @{$_}{qw(name lastName email address phone)} ] } @contacts ); # All done, print it out print $table;