简体   繁体   English

尝试解析csv文件时声明错误

[英]Errors in declaration when trying to parse a csv file

I'm trying to parse a CSV file that is formatted like this: 我正在尝试解析格式如下的CSV文件:

    dog cats,yellow blue tomorrow,12445
    birds,window bank door,-novalue-
    birds,window door,5553
    aspirin man,red,567

(there is no value where -novalue- is written) (在写入-novalue-的位置没有值)


use strict;
use warnings;


my $filename = 'in.txt';
my $filename2 = 'out.txt';

open(my $in, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";

my $word = "";

while (my $row = <$in>) {
    chomp $row;

    my @fields = split(/,/,$row);

    #Save the first word of the second column
    ($word) = split(/\s/,$fields[1]);

    if ($word eq 'importartWord')
    {
        printf $out "$fields[0]".';'."$word".';'."$fields[2]";
    }   
    else #keep as it was
    {
        printf $out "$fields[0]".';'."$fields[1]".';'."$fields[2]";
    }

Use of uninitialized value $word in string ne at prueba7.pl line 22, <$in> line 10.

No matter where I define $word I cannot stop receiving that error and can't understand why. 不管我在哪里定义$ word,我都无法停止接收该错误,也无法理解原因。 I think I have initialized $word correctly. 我想我已经正确初始化了$ word。 I would really appreciate your help here. 非常感谢您的帮助。

Please if you are going to suggest using Text::CSV post a working code example since I haven't been able to apply it for the propose I have explained here. 如果您要使用Text :: CSV提出建议,请发布一个工作代码示例,因为我无法将其应用于在此说明的提议。 That's the reason I ended up writing the above code. 这就是我最终编写上述代码的原因。


PD: Because I know you are going to ask for my previous code using Text::CSV, here it is: PD:因为我知道您将使用Text :: CSV询问我以前的代码,所以它是:

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

use Text::CSV;

my $csv = Text::CSV->new({ sep_char => ';', binary => 1 }) or 
                    die "Cannot use CSV: ".Text::CSV->error_diag ();


#directorio donde esta esc_prim2.csv
my $file = 'C:\Users\Sergio\Desktop\GIS\perl\esc_prim2.csv';
my $sal = 'C:\Users\Sergio\Desktop\GIS\perl\esc_prim3.csv';


open my $data, "<:encoding(utf8)", "$file" or die "$file: $!";
open my $out, ">:encoding(utf8)", "$sal" or die "$sal: $!";

$csv->eol ("\r\n");


#initializing variables
my $row = "";
my $word = "";
my $validar = 0;
my $line1 = "";
my @mwords = [""];#Just a try to initialize mwords... doesn't work, error keeps showing


#save the first line with field names on the other file
$line1 = <$data>;
$csv->parse($line1);
my @fields = $csv->fields();
$csv->print($out,[$fields[0], $fields[1], $fields[2]]);



while ($row = <$data>) {

    if ($csv->parse($row)) {
        @fields = $csv->fields();

        #save first word of the field's second element 
        @mwords = split (/\s/, $fields[1]);

        #keep the first one
        $word = $mwords[0];

        printf($mwords[0]);

        #if that word is not one of SAN, EL y LA... writes a line in the new file with the updated second field.
        $validar = ($word ne 'SAN') && ($word ne 'EL') && ($word ne 'LA');
        if ($validar)
        {
            $csv->print($out,[$fields[0], $word, $fields[2]]);
        }
        else { #Saves the line in the new file as it was in the old one.
            $csv->print($out,[$fields[0], $fields[1], $fields[2]]);
        }


    } else {#error procesing row
        warn "La row no se ha podido procesar\n";
    }
}

close $data or die "$file: $!";
close $out or die "$sal: $!";

Here the line where $validar is declared brings the same error of "uninitialized value" although I did it. 尽管我这样做了,但在这里声明$ validar的行带来了“未初始化的值”相同的错误。

I also tried the push @rows, $row; 我也尝试了推@rows,$ row; approach but I don't really know how to handle the $rows[$i] since they are references to arrays (pointers) and I know they can't be operated as variables... Couldn't find a working example on how to use them. 方法,但我真的不知道如何处理$ rows [$ i],因为它们是对数组(指针)的引用,并且我知道它们不能作为变量操作...找不到如何工作的有效示例使用它们。

The error message you provided ends with: line 22, <$in> line 10. but your question doesn't show line 10 of the data ( $in ) requiring some speculation in this answer - but, I'd say that the second field, $field[1] , of line 10 of in.txt is empty. 您提供的错误消息以line 22, <$in> line 10.结尾line 22, <$in> line 10.但是您的问题没有显示数据的第10行( $in ),因此需要对此答案进行推测-但是,我想说的是第二条in.txt的第10行的$field[1]为空。

Consequently, this line: ($word) = split(/\\s/,$fields[1]); 因此,此行: ($word) = split(/\\s/,$fields[1]); is causing $word to be undefined. 导致未定义$word As a result, some use of it latter - be it the ne operator (as displayed in the message) or anything else is going to generate an error. 结果,后者的某些用法-它是ne运算符(如消息中显示的那样)或其他任何东西都会产生错误。

As an aside - there's little point in interpolating a variable in a string on its own; 顺便说一句-单独在字符串中插入变量没有什么意义; instead of "$fields[0]" , say $fields[0] unless you're going to put something else in there, like "$fields[0];" 而不是"$fields[0]" ,说$fields[0]除非你打算把别的东西在里面,比如"$fields[0];" . You may want to consider replacing 您可能要考虑更换

printf $out "$fields[0]".';'."$word".';'."$fields[2]"; 

with

printf $out $fields[0] . ';' . $word . ';' . $fields[2];

or 要么

printf $out "$fields[0];$word;$fields[2]"; 

Of course, TMTOWTDI - so you may want to tell me to mind my own business instead. 当然是TMTOWTDI-因此,您可能要告诉我自己做生意。 :-) :-)

I think you're misunderstanding the error. 我认为您误会了错误。 It's not a problem with the declaration of the variable, but with the data that you're putting into the variable. 声明变量不是问题,但要放入变量中的数据不是问题。

Use of uninitialized value 使用未初始化的值

This means that you are trying to use a value that is undefined (not undeclared). 这意味着您正在尝试使用未定义(未声明)的值。 That means you are using a variable that you haven't given a value. 这意味着您正在使用一个没有给定值的变量。

You can get more details about the warning (and it's a warning, not an error) by adding use diagnostics to your code. 通过在代码中添加use diagnostics ,可以获取有关警告的更多详细信息(这是警告,而不是错误)。 You'll get something like this: 您将获得如下内容:

(W uninitialized) An undefined value was used as if it were already defined. (W未初始化)使用未定义的值,就好像它已经被定义一样。 It was interpreted as a "" or a 0, but maybe it was a mistake. 它被解释为“”或0,但可能是一个错误。 To suppress this warning assign a defined value to your variables. 要消除此警告,请为变量分配一个已定义的值。

To help you figure out what was undefined, perl will try to tell you the name of the variable (if any) that was undefined. 为了帮助您弄清未定义的内容,perl会尝试告诉您未定义的变量的名称(如果有)。 In some cases it cannot do this, so it also tells you what operation you used the undefined value in. Note, however, that perl optimizes your program and the operation displayed in the warning may not necessarily appear literally in your program. 在某些情况下,它不能执行此操作,因此它还会告诉您使用了未定义值的操作。但是,请注意,perl会优化您的程序,警告中显示的操作不一定会在您的程序中真实显示。 For example, "that $foo" is usually optimized into "that " . 例如,通常将“ that $ foo”优化为“ that”。 $foo, and the warning will refer to the concatenation (.) operator, even though there is no . $ foo,即使没有,警告也将引用串联(。)运算符。 in your program. 在您的程序中。

So, when you're populating $word , it's not getting a value. 因此,当您填充$word ,它没有值。 Presumably, that's because some lines in your input file have an empty record there. 大概是因为输入文件中的某些行在那里有空记录。

I have no way of knowing whether or not that's a valid input for your program, so I can't really give any helpful suggestions on how to fix this. 我无法知道这是否对您的程序有效,因此我无法就如何解决此问题提供任何有用的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM