tags:

views:

111

answers:

1

Hello, what is the right way to get here a beautiful output ( all lines the same indent )?

#!/usr/bin/env perl
use warnings;
use strict;
use DBI;

my $phone_book = [ [ qw( name number ) ],
            [ 'Kroner', 123456789 ],
            [ 'Holler', 123456789 ],
            [ 'Mühßig', 123456789 ],
            [ 'Singer', 123456789 ],
            [ 'Maurer', 123456789 ],
];

my $dbh = DBI->connect( "DBI:CSV:", { RaiseError => 1 } );
$dbh->do( qq{ CREATE TEMP TABLE phone_book AS IMPORT( ? ) }, {}, $phone_book );

my $sth = $dbh->prepare( qq{ SELECT name, number FROM phone_book } );
$sth->execute;

my $array_ref = $sth->fetchall_arrayref();

for my $row ( @$array_ref ) {
    printf "%9s %10s\n", @$row;
}

# OUTPUT:

#   Kroner  123456789
#   Holler  123456789
# Mühßig  123456789
#   Singer  123456789
#   Maurer  123456789
+3  A: 

I haven't been able to reproduce it, but loosely speaking what seems to be happening is that it's a character encoding mismatch. Most likely your Perl source file has been saved in UTF-8 encoding. However you have not enabled use utf8; in the script. So it's interpreting each of the non-ASCII German characters as being two characters and setting the padding accordingly. But the terminal you're running on is also in UTF-8 mode so the characters print correctly. Try adding use warnings; and I'll bet you get a warning printed, and I would not be surprised if adding use utf8; actually fixes the problem.

Dan
"use warnings;" is already there, and when I add "use utf8" the third row looks like this : "M�h�ig 123456789". Reading from a file I have the same problem.
sid_com
Ok, with "binmode STDOUT, 'encoding(utf8)'" enabled too it works.
sid_com
reading from the file I do this:"binmode STDOUT, 'encoding(utf8)';use Encode qw( decode );for my $row ( @$array_ref ) { printf "%9s %10s\n", map{ decode 'UTF-8', $_ } @$row;}"end the output looks fine.
sid_com
@Dan: I had warnings enabled, but I didn't get any warnings.
sid_com