2012-07-23 98 views

回答

7

是的。如perldoc -f open中所述,您可以打开文件句柄来标量变量。

my $data = <<''; 
line1 
line2 
line3 

open my $fh, '<', \$data; 
while (<$fh>) { 
    chomp; 
    print "[[ $_ ]]\n"; 
} 

# prints 
# [[ line1 ]] 
# [[ line2 ]] 
# [[ line3 ]] 
14

如果您确实需要,您可以打开一个文件句柄。

use strict; 
use warnings; 

my $lines = "one\ntwo\nthree"; 
open my $fh, "<", \$lines; 

while(<$fh>) { 
    print "line $.: $_"; 
} 

另外,如果你已经有了在内存中的东西,无论如何,你可能只是它分割成一个数组:

my @lines = split /\n/, $lines; # or whatever 
foreach my $line(@lines) { 
    # do stuff 
} 

这可能会更容易阅读和维护的路线。

+2

一个可能的理由这样做是'开放ARGV的伎俩, '<',\ $ default_data除非@ ARGV'那么读取'<>'将使用默认数据,除非传入文件。 – 2012-07-23 03:44:37