2012-04-11 60 views
0

如果我们设置一个这样的指定格式。有什么办法可以复制输出并将其放入文件中。把格式化的输出放在一个文件中,perl格式

PS:当我使用严格的,它显示“全局符号‘$计数器’需要明确包名在aggregator.pl第19行”。这是什么造成的?我用本地来定义它的范围,所以我有点困惑。希望有人能给我一个回应。 THX很多

enter code here 

# Setup includes 
# use strict; 
use XML::RSS; 
use LWP::UserAgent; 
# Declare variables for URL to be parsed 
my $url2parse; 
# Get the command-line argument 
my $arg = shift; 
# Create new instance of XML::RSS 
my $rss = new XML::RSS; 
# Get the URL, assign it to url2parse, and then parse the RSS content 
$url2parse = get($arg); 
die "Could not retrieve $arg" unless $url2parse; 
$rss->parse($url2parse); 
#create arrays to hold data 
my @titles; 
local $counter = 0; 

#open file and write .txt output to it 
open my $fh, ">output.txt" or die "File creation failed: $!"; 

# Print the channel items 
foreach my $item (@{$rss->{'items'}}) { 
    $titles[$counter] = $item->{'title'}; 
&format_output($item->{'title'}); 
$counter++; 
} 
sub get { 
    my $url = shift; 
    my $ua = LWP::UserAgent->new(); 
    my $res = $ua->get($url); 
    die ("Could not retrieve $url: " . $res->status_line) unless($res->is_success); 
    return $res->content; 
} 

sub format_output { 
    local($title) = @_; 
    $~ = "MYFORMAT"; 
    write; 
    print $fh @_; 
} 
format MYFORMAT = 

======================= 
    Title :~ ^<<<<<<<<< 
$title 
======================= 
. 

回答

1

write带有一个可选的文件句柄参数,所以你可以用write $fh更换print。你需要为了设置$~为您的文件句柄以及为STDOUT使用1参数select

local不声明名称的范围,它只是保存和恢复上的范围进入/退出的值。使用ouruse vars来声明变量的作用域。

+1

不错!你真的帮我过。非常感谢 – 2012-04-11 04:50:39

+1

使用'our'而不是'vars',现在被认为是_obsolete_。 – 2012-04-11 06:04:01

+0

@rainzwr就这么预期,你将通过点击勾选只是答案的左边的“接受”正确的答案。这标志着它为未来的读者,并奖励答复的答复者。 – 2012-04-11 06:33:40