我有一个自己编写的 Perl 脚本,将其保存为 index.cgi
,它会从 TSV 读取短链接及其扩展表:
重定向.tsv:
$ head redirects.tsv
about http://tobilehman.com/about
gapminder http://www.gapminder.org/
speed http://speedof.me/
delete http://justdelete.me/
terms http://tosdr.org/
re https://www.debuggex.com/
1 http://www.diffen.com/difference/Diffen_vs_Wikipedia
2 http://arstechnica.com/information-technology/2013/10/google-fiber-now-explicitly-permits-home-servers/
3 https://www.senate.gov/legislative/LIS/roll_call_lists/roll_call_vote_cfm.cfm?congress=113
ifs http://tobilehman.com/blog/2013/10/19/revisiting-spaces-in-file-names/
索引.cgi:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
my $current_time = time();
my $file = "redirects.tsv";
open my $lines, $file or die "Could not open redirects.tsv";
my $redirect_html = "";
while ( my $line = <$lines> ) {
$line =~ /^([0-9a-z_-]+)\t(.*)/;
#$redirect_html = "$redirect_html\n<li><a href='$1'>tblh.mn/$1</a> ($2)</li>";
my $link = "http://tblh.mn/$1";
$redirect_html
= "$redirect_html<tr><td><a href='$link'>$link</td><td>→</td><td style='padding-left:15px'>$2</td></tr>\n";
}
print <<HTML;
<html>
<head>
<link href="/favicon.png" rel="icon">
<title>tblh.mn → tobilehman.com</title>
</head>
<body>
<h1>Current Time: $current_time</h1>
<h1>Short Links</h1>
<table>
$redirect_html
</table>
</body>
</html>
HTML
exit;
现在,链接按照后进后出的方式打印,但我希望它们以后进先出的方式打印。
我尝试使用 reverse(<$lines>)
来解决这个问题和<reverse($lines)>
,这两个都不起作用。我对 Perl 不太熟悉,所以如果这是一个菜鸟问题,请原谅我。
最佳答案
正如已经指出的,您可以使用 reverse
反转数组,或 File::ReadBackwards
做它的名字所暗示的事情。
此外,我想鼓励您在脚本中进行一些基本的错误检查:
- 始终包含
use strict;
和use warnings;
在每个脚本中。 - 包括
use autodie
任何时候您进行文件处理时。 - 在使用捕获变量之前,请确保您的正则表达式匹配。
风格上:
- 使用连接运算符构建字符串
$string .= "more string";
- 每当您想在字符串中包含双引号时,请使用
qq{ }
等替代分隔符。
包括这些更改以及其他一些小修复:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
print "Content-type: text/html\n\n";
my $current_time = time();
my $file = "redirects.tsv";
open my $fh, '<', $file;
my $redirect_html = "";
for ( reverse <$fh> ) {
chomp;
if ( my ( $shortlink, $full ) = /^([0-9a-z_-]+)\t(.*)/ ) {
my $link = "http://tblh.mn/$shortlink";
$redirect_html
.= qq{<tr><td><a href="$link">$link</td><td>→</td><td style="padding-left:15px">$full</td></tr>\n};
#$redirect_html .= "\n<li><a href='$1'>tblh.mn/$1</a> ($2)</li>";
}
}
print <<"HTML";
<html>
<head>
<link href="/favicon.png" rel="icon">
<title>tblh.mn → tobilehman.com</title>
</head>
<body>
<h1>Current Time: $current_time</h1>
<h1>Short Links</h1>
<table>
$redirect_html
</table>
</body>
</html>
HTML
exit;
关于perl - 反转从 CGI 脚本中的文件读取的行数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616725/