2013-08-22 4 views
1

무슨 일이 일어나고 있습니까? 나는 줄을 읽고 파일에 출력물을 인쇄하는 간단한 프로그램을 만들었다. 그러나 여기 Perl - 초기화되지 않은 변수

코드이고 그것의 설명이 코멘트에 ... 약간의 오차가 발생합니다 :

use warnings; 
use List::MoreUtils qw(indexes); 

my @array_words =(); 
my @array_split =(); 
my @array_of_zeros = (0); 
my $index = 0; 

open my $info, 'models/busquedas.csv'; 
open my $model, '>>models/model.txt'; 

#First while is to count the words and store it into an array 
while(my $line = <$info>) { 
    @array_split = regex($line); 
    for (my $i=0; $i < scalar(@array_split); $i++) { 
      # Get the index if the word is repeated 
     $index = indexes { $_ eq $array_split[$i] } $array_words[$i]; 
      # if the word is not repeated then save it to the array by 
      # checking the index 
     if ($index != -1){ push(@array_words, $array_split[$i]); } 
    } 
} 

print $model @array_words; 

sub regex{ 
    # get only basic info like: 'texto judicial madrid' instead of the full url 
    if ($_[0] =~ m/textolibre=/ and 
     $. < 3521239 && 
     $_[0] =~ m/textolibre=(.*?)&translated/) { 
     return split(/\+/, $_[0]); 
    } 
} 

내가 이해하지 못하는 오류는 다음과 같습니다

Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12216. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12216. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12216. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12217. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12217. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12217. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12217. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12217. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12218. 
Use of uninitialized value $index in numeric ne (!=) at classifier.pl line 21, <$info> line 12218. 

초기화되지 않은 이유는 무엇입니까 $index? 나는 그것을 선언하고 0 값으로 초기화했다! 어떻게 해결할 수 있습니까?

+0

나는 당신이'indexes' 함수가 어떻게 작동하는지 오해했다고 생각합니다. 하나의 요소가 아니라 반복 할 목록이 있어야합니다. 그것은 인덱스를 반환하고 이미 해당 아이템에 대한 인덱스를 가지고 있습니다 :'$ i'. – TLP

+0

왜 전체 배열이 아닌'@ array_words'의 단일 요소에서'indexes'를 호출합니까? – nwellnhof

+0

하지만 다른 언어에서 .indexof() 함수를 사용하려면 어떻게해야합니까? @nwellnhof –

답변

1

당신은 0으로 변수를 초기화,하지만 당신은

$index = indexes { $_ eq $array_split[$i] } $array_words[$i]; 

($array_words[$i]$array_split[$i] EQ를하지 않기 때문에) 기능은 아마 미확정를 반환으로 그 값을 변경합니다. 목록에 하나의 요소 만 있으므로 그렇지 않으면 하나를 반환합니다.

현재 루프 외부에서 변수를 초기화하지 않는 것이 좋지 않은 경우 루프 외부에서 변수를 초기화하는 것은 좋지 않은 방법입니다. 으로 채우는 동일한 줄에 my $index을 선언 할 수 있습니다.

+0

'indexes'는 블록이 true로 평가 한리스트 인덱스를 반환합니다. 이와 같이 스칼라 문맥에서 (잘못) 사용된다면, 결과는 * last *와 같은 색인이 될 것이고, 목록의 어떤 요소도 기준을 만족하지 않는다면'undef'가 될 것입니다. 목록의 * 두 번째 요소가 테스트를 통과 한 마지막 요소가 아니면 * "* * *"하나를 반환하지 않습니다. – Borodin

+0

@ 보로딘 : 오 이런? 'perl -MList :: MoreUtils = indexes -E '$ x = indexes {$ _ lt "c"} qw/cbdea /; $ x "는'2'를 반환하지만 반환되는 인덱스는 1과 4입니다. – choroba

+0

내 시스템에'4 '라고 알려줍니다. 'List :: MoreUtils'가 최신 버전입니까? 'Perl -MList :: MoreUtils -E '명령을 실행하면 $ List :: MoreUtils :: VERSION'의 최신 버전은 0.33입니다. – Borodin

0

관찰 된 바와 같이, indexes 서브 루틴은 그렇게 작동하지 않습니다. 블록이 으로 평가되는 인덱스의 목록을 반환합니다. 이와 같이 스칼라 컨텍스트에서 사용하는 것은 잘못입니다.

라이브러리를 사용하려면 any도 입력해야합니다. List::MoreUtils. 코드는 다음과 같습니다.

while(my $line = <$info>) { 
    @array_split = regex($line); 
    for my $word (@array_split) { 
     push @array_words, $word unless any { $_ eq $word } @array_words; 
    } 
} 

그러나 나는 당신이 훨씬 더 단순한 것을 원한다고 생각합니다. Perl 해시가 자신의 코드를 이해함에 따라 필요한 것을 할 수 있습니다.

나는 이와 같이 프로그램을 리팩터링했습니다. 나는 그것이 도움이되기를 바랍니다.

본질적으로 줄의 각 "단어"는 아직 해시에 없으면 @array_words에 푸시됩니다.

regex 서브 루틴에 버그가있는 것 같습니다. 문

return split(/\+/, $_[0]); 

전체 라인을 분할하고 결과를 반환합니다. 나는 일반적으로 당신이 open 통화가 성공했는지 확인해야이

return split /\+/, $1; 

처럼, 당신은 단지 추출 한 URL의 단지 쿼리 부분을 분할한다고 생각합니다. autodie pragma를 추가하면 암시 적으로이 작업이 수행됩니다.

use strict; 
use warnings; 
use autodie; 

open my $info, '<', 'models/busquedas.csv'; 
open my $model, '>>', 'models/model.txt'; 

my %unique_words; 
my @array_words; 

#First while is to count the words and store it into an array 
while(my $line = <$info>) { 
    for my $word (regex($line)) { 
    push @array_words, $word unless $unique_words{$word}++; 
    } 
} 

print $model "$_\n" for @array_words; 

sub regex { 

    my ($line) = @_; 

    # get only basic info like: 'texto judicial madrid' instead of the full url 
    return unless $line =~ /textolibre=/ and $. < 3521239; 
    if ($line =~ /textolibre=(.*?)&translated/) { 
    return split /\+/, $1; 
    } 
} 
관련 문제