perl使用print输入数据到文件

#!usr/bin/perl
use utf8;


#引入utf8模块 脚本内的字符串使用utf8作为编码格式
binmode(STDOUT,":encoding(gbk)");
#标准输出使用gbk作为编码格式,也可以把gbk改为gb2312
binmode(STDIN,":encoding(gbk)");
#如果涉及到输入流,例如读文件,不加这条读中文文件会出现乱码
binmode(STDERR,":encoding(gbk)");
#如果异常错误中的字符串有中文,请加上STDERR,否则也会出现乱码


open( DATA, "> Error.txt" )
  || die "Unable to open error for write! - $!\n";
  
%IOLIST=('李白',{'age','18','height','185','weight','60kg'},
'李1',{'age','18','height','185','weight','60kg'},
'李2',{'age','19','height','180','weight','60kg'},
'李3',{'age','28','height','181','weight','60kg'},
'李4',{'age','21','height','182','weight','60kg'},
'李5',{'age','22','height','183','weight','60kg'},
'李6',{'age','23','height','184','weight','60kg'},
'李7',{'age','24','height','188','weight','60kg'},
'李8',{'age','25','height','187','weight','60kg'},
'李9',{'age','26','height','186','weight','60kg'},
'李10',{'age','27','height','189','weight','60kg'}
);
dumplist(\%IOLIST);

sub dumplist
{
    my $LIST = shift;
    my $legend = 0;
    foreach $item (sort keys %$LIST)
    {
        my @attributes = ();
        my @legen = ();
        print "$item:\n";
        foreach $attr (sort keys %{$$LIST{$item}})
        {
            push(@legen, $attr);
            push(@attributes, $LIST->{$item}{$attr})
        }
        print @legen , "\n" if $legend == 0;#打印数组,ageheightweight
        $legend++, print DATA "item:", join(',', @legen), "\n\n" if $legend == 0;
        print DATA "$item:\t", join(',    ',@attributes),"\n\n";
    }
}

输出结果:

D:\>Error.pl
李1:
ageheightweight
Wide character in print at D:\Error.pl line 47.
李10:
Wide character in print at D:\Error.pl line 47.
李2:
Wide character in print at D:\Error.pl line 47.
李3:
Wide character in print at D:\Error.pl line 47.
李4:
Wide character in print at D:\Error.pl line 47.
李5:
Wide character in print at D:\Error.pl line 47.
李6:
Wide character in print at D:\Error.pl line 47.
李7:
Wide character in print at D:\Error.pl line 47.
李8:
Wide character in print at D:\Error.pl line 47.
李9:
Wide character in print at D:\Error.pl line 47.
李白:
Wide character in print at D:\Error.pl line 47.

Error.txt

item:age,height,weight

李1:    18,    185,    60kg

李10:    27,    189,    60kg

李2:    19,    180,    60kg

李3:    28,    181,    60kg

李4:    21,    182,    60kg

李5:    22,    183,    60kg

李6:    23,    184,    60kg

李7:    24,    188,    60kg

李8:    25,    187,    60kg

李9:    26,    186,    60kg

李白:    18,    185,    60kg

 

posted @ 2021-04-01 15:05  WellMandala  阅读(1145)  评论(0编辑  收藏  举报