2016-05-31 66 views
1

我试图写一个Perl程序采取两种不同的输入:Perl程序通过STDIN

print "Enter the filename:"; 
    $filename = readline STDIN; 

    print "Enter the string to be compared"; 
    $string1 = readline STDIN; 

要一气呵成这两个输入相结合,我做了以下内容:

print "Enter the filename and string to be compared:"; 
    my $input1 = readline STDIN; 
    my @name = split(' ',$input1); //split the input parameters by space 
    $filename = $name[0]; 
    $string1 = $name[1]; 
    chomp $string1; 

这是功能性代码,我想知道是否有其他方法可以为此逻辑实现更优化的版本?

感谢, DD

+2

定义*优化*! – salva

+0

我不会建议你以这种方式进行优化。如果文件名将包含空格,你会做什么?逻辑会增加。看@ mkHun不要。 –

+0

看看http://perldoc.perl.org/Getopt/Long.html – Toto

回答

5

这是我们所优化为您获取有关kite什么。在确定需要之前,不要试图手动优化代码。鉴于这是一个等待IO,它将不重要,因为IO比你在代码中做的任何事都慢。

但如果你的意思是更简洁

print "Enter the filename and string to be compared:"; 
chomp (my ($filename, $string) = split ' ', <>); 

这需要<> - 这是一个神奇的文件句柄,并读取要么标准输入或命令行中指定的文件名。 (像grep/sed/awk那样工作)。

我们将它在标量上下文中分割 - 然后将值从split分配到列表分配$filename$string。然后它将被切掉以消除换行。

2

Perl的秘密

use warnings; 
use strict; 
print "Enter the filename and string to be compared:"; 
chomp(my @ar = (~~<>, ~~<>)); 
print @ar;   
+3

虽然很聪明,但我并不确信'perl secret'中的任何东西都是你应该在实际代码中使用的东西,因为它很晦涩。 – Sobrique

+0

'标量(<>)'或'“”。<>'会少一些“秘密”。 //注意,在返回EOF之后从文件句柄中读取是一个不允许的,所以这种方法本质上是有缺陷的。 – ikegami

0

尝试使用代码波纹管与 `COMAND:Perl的your_script.pl -file_name 'SOME_FILE' -string 'some_string'

use Getopt::Long; 

my ($file_name, $string); 
GetOptions(
'file_name=s' => \$file_name, 
'string=s' => \$string, 
) or die "Could not parse options"; 

if($file_name eq $string) 
{ 
print "The file name is the same as the string\n"; 
}else{ 
print "Not a match\n"; 
}