在串联(。)中使用未初始化的值\ $ price或在./11LIST02.pl行中使用字符串

时间:2013-11-25 06:07:10

标签: perl initialization

我有这个数据集

The Lion King!
Tumbleweed Connection!Elton John!123.32
Photographs & Memories!Jim Croce!4.95
Heads & Tales!Harry Chapin!12.50

这个脚本给了我未初始化的错误

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

open( my $filehandle , "<", $ARGV[0]) || die $!;
my @lines = <$filehandle> ;
close($filehandle) ;

foreach (@lines) {
    chop;
    my ($album ,$artist,$price );
    ($album, $artist, $price) = (split(/!/));
    print ("Album=$album    Artist=$artist    Price=$price\n");
    }

错误

 casper_mint@casper-mint-dell ~/david_mendinets. $ ./11LIST02.pl FORMAT.DAT
 Use of uninitialized value $price in concatenation (.) or string at ./11LIST02.pl line 13.
Album=The Lion King    Artist=    Price=
Album=Tumbleweed Connection    Artist=Elton John    Price=123.32
Album=Photographs & Memories    Artist=Jim Croce    Price=4.95
Album=Heads & Tales    Artist=Harry Chapin    Price=12.50
Use of uninitialized value $album in concatenation (.) or string at ./11LIST02.pl line  13.
Use of uninitialized value $artist in concatenation (.) or string at ./11LIST02.pl line 13.
Use of uninitialized value $price in concatenation (.) or string at ./11LIST02.pl line 13.
Album=    Artist=    Price=

所以我修复了脚本 - 但我仍然收到一个错误。

  1 #!/usr/bin/perl
  2 use warnings;
  3 use strict;
  4
  5 open( my $filehandle , "<", $ARGV[0]) || die $!;
  6 my @lines = <$filehandle> ;
  7 close($filehandle) ;
  8
  9 foreach (@lines) {
 10     chop;
 11     my $album ="";
 12     my $artist ="";
 13     my  $price ="" ;
 14     ($album, $artist, $price) = (split(/!/));
 15     if (length $album) {
 16     print ("Album=$album    Artist=$artist    Price=$price\n");
 17     }
 18     elsif (length $price) {
 19     print ("Album=$album    Artist=$artist    Price=$price\n");
 20     }
 21 }



casper_mint@casper-mint-dell ~/david_mendinets. $ ./11LIST02.pl FORMAT.DAT
Use of uninitialized value $price in concatenation (.) or string at ./11LIST02.pl line 16.
Album=The Lion King    Artist=    Price=
Album=Tumbleweed Connection    Artist=Elton John    Price=123.32
Album=Photographs & Memories    Artist=Jim Croce    Price=4.95
Album=Heads & Tales    Artist=Harry Chapin    Price=12.50
casper_mint@casper-mint-dell ~/david_mendinets. $

我无法摆脱最后一个错误 - 我确实理解它

2 个答案:

答案 0 :(得分:2)

尝试从第11-14行重构代码,如下所示:

my ($album, $artist, $price) = (split(/!/));
$album ||= "";
$artist ||= "";
$price ||= "" ;

将值拆分为变量,然后在未定义任何值的情况下指定默认值(“”)。这应该可以解决你的问题。

答案 1 :(得分:2)

似乎分割的行少于三个元素,因此可以分配默认值

$_ //= "" for 
  my ($album, $artist, $price) = split /!/;

//=仅在提到的变量为undef时指定空字符串,而不是在它们通常评估为false时指定。