2012-06-19 4 views
3

특수 파일 핸들 <STDIN>에서 읽는 Perl 모듈을 원하고 이것을 서브 루틴으로 전달합니다. 내 코드를 볼 때 내 뜻을 이해하게 될 것입니다.Perl 서브 루틴으로 파일 핸들을 전달하고 읽는 방법?

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

use lib '/usr/local/custom_pm' 
package Read_FH 

sub read_file { 
my ($filein) = @_; 
open FILEIN, $filein or die "could not open $filein for read\n"; 
# reads each line of the file text one by one 
while(<FILEIN>){ 
# do something 
} 
close FILEIN; 

오른쪽 이제 서브 루틴이 하나 파일 하나의 각 라인을 인수로 ($filein에 저장) 파일 이름을 사용하여 파일 핸들을 사용하여 파일을 열고, 읽고 : 여기 전에 그것이 얼마나입니다 미세 핸들 사용.

대신 파일 이름을 <STDIN>에서 가져 와서 변수에 저장 한 다음이 변수를 인수로 서브 루틴에 전달하고 싶습니다. 메인 프로그램에서 :

$file = <STDIN>; 
$variable = read_file($file); 

모듈의 서브 루틴은 다음과 같습니다 :

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

use lib '/usr/local/custom_pm' 
package Read_FH 

# subroutine that parses the file 
sub read_file { 
my ($file)= @_; 
# !!! Should I open $file here with a file handle? !!!! 

# read each line of the file 
while($file){ 
# do something 
} 

는 아무도 내가이 작업을 수행 할 수있는 방법을 알고 있나요? 나는 어떤 제안을 주셔서 감사합니다.

+0

을 그냥 그래서 당신이에 대한 CPAN 모듈을 원하는 수행을 제대로 이해하거나를 얻을 수 있도록 모듈을 변경하는 데 도움 싶어 filename from ''? – simbabque

+0

파일 이름이 ''이되도록 내 모듈을 변경하는 데 도움이 필요합니다. – cooldood3490

+0

두 줄의 코드를 모듈에 넣으려고 했습니까? – simbabque

답변

6

일반적으로 어휘 파일 핸들러를 사용하는 것이 좋습니다. 그것은 bareword 대신 파일 핸들러를 포함하는 어휘 변수입니다.

다른 변수와 마찬가지로 전달할 수 있습니다. File::Slurp에서 read_file을 사용하면 별도의 파일 핸들러가 필요하지 않으므로 내용을 변수로 분할합니다.

가능한 한 빨리 열린 파일 핸들을 닫는 것이 좋습니다. 실제로 전체 파일 내용 만 가져와야하는 경우이 방법을 사용하는 것이 좋습니다. 추가 모듈없이

use strict; 
use warnings; 
use autodie; 
use File::Slurp; 

sub my_slurp { 
    my ($fname) = @_; 
    my $content = read_file($fname); 

    print $content; # or do something else with $content 

    return 1; 
} 

my $filename = <STDIN>; 
my_slurp($filename); 

exit 0; 

: 파일 : 소리내어 먹으로

use strict; 
use warnings; 
use autodie; 

sub my_handle { 
    my ($handle) = @_; 
    my $content = ''; 

    ## slurp mode 
    { 
     local $/; 
     $content = <$handle> 
    } 

    ## or line wise 
    #while (my $line = <$handle>){ 
    # $content .= $line; 
    #} 

    print $content; # or do something else with $content 

    return 1; 
} 

my $filename = <STDIN>; 
open my $fh, '<', $filename; 
my_handle($fh); # pass the handle around 
close $fh; 

exit 0; 
+0

어휘 파일 핸들에 대한 설명. 나는'File :: Slup'이 아마도 자신의 코드보다 낫다고 동의한다. – simbabque

+0

감사합니다 mugen. 나는 어휘 파일 핸들과 [File :: Slurp] (http://search.cpan.org/~uri/File-Slurp-9999.19/lib/File/Slurp.pm) 모듈을 사용하는 법을 배워야 만한다고 생각한다. – cooldood3490

3

내가 @mugen의 켄이치 동의, 그의 해결책은 자신을 구축하는 것보다 그것을 할 수있는 더 좋은 방법입니다. 커뮤니티에서 테스트 한 자료를 사용하는 것이 좋습니다. 어쨌든, 당신이 원하는 것을하기 위해 자신의 프로그램에 할 수있는 변경 사항은 다음과 같습니다. 나는 그것을 실행하는 경우

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

package Read_FH; 

sub read_file { 
    my $filein = <STDIN>; 
    chomp $filein; # Remove the newline at the end 
    open my $fh, '<', $filein or die "could not open $filein for read\n"; 
    # reads each line of the file text one by one 
    my $content = ''; 
    while (<$fh>) { 
     # do something 
     $content .= $_; 
    } 
    close $fh; 

    return $content; 
} 

# This part only for illustration 
package main; 

print Read_FH::read_file(); 

, 그것은 다음과 같습니다

[email protected]:~/scratch$ cat test 
this is a 
testfile 

with blank lines. 
[email protected]:~/scratch$ perl test.pl 
test 
this is a 
testfile 

with blank lines. 
관련 문제