2011-09-09 4 views
1

,perl 배열에서 여러 값을 가져 오는 가장 좋은 방법은 무엇입니까? 우선

, 난

my @dataRecord = split(/\n/); 

다음에,이 같은 시험 라인을 얻을 수있는 배열 데이터 레코드에 필터링이 같은 배열로 dataRecord 얻을

@dataRecord = grep(/test_names/,@dataRecord); 

다음으로, 나는이 같은 테스트 라인에서 테스트 이름을 얻을 필요가

my ($test1_name,$test2_name,$test3_name) = getTestName(@dataRecord); 

    sub getTestName 
    { 
     my $str = shift @_; 
     # testing the str for data and 
     print str,"\n"; # This test point works in that I see the whole test line. 
     $str =~ m{/^test1 (.*), test2 (.*), test3 (.)/}; 
     print $1, "\n"; # This test point does not work. 
     return ($1,$2,$3); 
    } 

이 작업을 수행하는 더 좋은 방법이 있습니까?

+0

돌아 오기 위해? –

답변

4

필요한 구문을 줄이면서 작업을 함께 연결할 수 있습니다. 이것은 구문 잡음을 줄이면서 프로그램의 중요한 부분을 강조하는 장점이 있습니다.

my @test = map m{/^test1 (.*), test2 (.*), test3 (.)/}, 
      grep /test_names/, 
      split /\n/; 

# use $test[0], $test[1], $test[2] here 

당신은 문제를 디버깅하려는 경우,지도 및 GREP은 오류 검사 코드를 삽입하기 쉽게 만드는 블록을 수행 할 수 있습니다 여기에

my @test = map { 
       if (my @match = m{/^test1 (.*), test2 (.*), test3 (.)/}) { 
        @match 
       } else { 
        die "regex did not match for: $_" 
       } 
      } # no comma here 
      grep /test_names/, 
      split /\n/; 

가 배열에서 할당하는 몇 가지 방법입니다을 직접 질문과 관련, 그러나 아마 유용되지 않은 :

:

my ($zero, $one, $two) = @array; 
my (undef, $one, $two) = @array; 
my (undef, undef, $two) = @array; # better written `my $two = $array[2];` 

my ($one, $two) = @array[1, 2]; # note that 'array' is prefixed with a @ 
my ($one, $two) = @array[1 .. 2]; # indicating that you are requesting a list 
            # in turn, the [subscript] sees list context 
my @slice = @array[$start .. $stop]; # which lets you select ranges 

서브 루틴에 인수 압축을 풀려면 name => value쌍 취하는 방법에

my ($first, $second, @rest) = @_; 

15,: 변수 목록을 반환 값을 할당하여, 예를 들어,리스트 문맥에서 m// 연산자를 사용하여 매칭 표현식의리스트를 얻을 수

my ($self, %pairs) = @_; 
+0

감사합니다. Eric, @test 배열에 null 값이 입력되지 않도록하려면 어떻게해야합니까? –

+0

어떤 유형의 null입니까? 값은 정의되지 않을 수 있으며,이 경우 grep이 정의됩니다. 값은 길이,'grep 길이, ... '를 가질 수 없습니다. 값은 0 일 수 있습니다. 'grep $ _! = 0, ...'. 아니면 거짓 일 수 있습니다. 'grep $ _, ...'. 잘못된 값이 나타나는 지점에서 처리 스택에 이들 중 하나를 추가하십시오. –

+0

다시 감사드립니다. Eric, 값이 정의되지 않은 것처럼 들리는 패턴 일치 (m //) 오류에서 초기화되지 않은 값 $ str을 사용 중입니다. grep이 각 데이터 레코드를 캡처하기 위해 필터 데이터 만 캡처한다고 생각했기 때문에 이것은 이상한 오류입니다. –

0

을 (당신이 현재 서브 루틴 호출과 같이). 그래서, 당신은 훨씬 더 간단한 구조와 서브 루틴을 대체 할 수

my $str = shift @dataRecord; 
my ($test1_name, $test2_name, $test3_name) = 
    $str =~ m/^test1 (.*), test2 (.*), test3 (.)/; 

또는, for 루프를 사용하면 @dataRecord 배열의 각 요소에 대해이 작업을 수행하려면 : 당신이 기대하는 어떤 값

for my $str (@dataRecord) { 
    my ($test1_name, $test2_name, $test3_name) = 
     $str =~ m/^test1 (.*), test2 (.*), test3 (.)/; 
} 
관련 문제