kr8*_*r85 2 perl diamond-operator
如何直接将菱形运算符中的值传递给函数(sub)?
我试过了:
#!/usr/bin/perl
use Math::Complex;
#quadraticEq - quadratic equation with parameters a ,b ,c
sub quadraticEq {
print "\nx1= ",
($_[1]*$_[1]-sqrt($_[1]*$_[1]-4*$_[0]*$_[2]))/(2*$_[0]),
"\nx2= ",
($_[1]*$_[1]+sqrt($_[1]*$_[1]-4*$_[0]*$_[2]))/(2*$_[0]);
}
print 'Enter Numbers:';
quadraticEq(<>,<>,<>); #here
Run Code Online (Sandbox Code Playgroud)
但是当我为每个函数参数输入数字时,我需要输入EOF.它表现得像@array=<>.我希望它表现得像$var=<>.所以输入应该如下所示:
Enter Numbers: 5 4 3
Run Code Online (Sandbox Code Playgroud)
我会向你展示几个最佳实践,同时我会帮助你解决问题......
#!/usr/bin/perl
use strict; # strict/warnings helps detect lots of bugs and logic issues,
use warnings; # so always use them
use Math::Complex; # WHITESPACE IS YOUR FRIEND
#quadraticEq - quadratic equation with parameters a ,b ,c
sub quadraticEq{
# Shift out your subroutine variables one at a time, or assign them to a list.
my ($a, $b, $c) = @_;
print "\nx1= ",
($b*$b-sqrt($b*$b-4*$a*$c))/(2*$a), # You're wrong on your formula btw
"\nx2= ",
($b*$b+sqrt($b*$b-4*$a*$c))/(2*$a);
}
print 'Enter Numbers: ';
# Perl only supports reading in a line at a time, so... if you want all your
# inputs on one line, read one line.
# EDIT: That's not strictly true, since you can change the input record separator,
# but it's just simpler this way, trust me.
my $line = <>;
# Then you can split the line on whitespace using split.
my @coefficients = split /\s+/, $line;
# You should check that you have at least three coefficients and that they
# are all defined!
quadraticEq(@coefficients);
Run Code Online (Sandbox Code Playgroud)
<>始终在列表上下文中调用函数参数列表中的裸运算符.但是有很多方法可以强制你想要的标量上下文:
quadraticEq(scalar <>, scalar <>, scalar <>);
quadraticEq("" . <>, "" . <>, "" . <>);
quadraticEq(0 + <>, 0 + <>, 0 + <>); # if you want to evaluate as numbers anyway
Run Code Online (Sandbox Code Playgroud)
请注意,<>在标量上下文中将从输入读取到下一个"记录分隔符".默认情况下是系统的换行符,因此上面代码的默认行为是从每行读取单独的值.如果(如原始帖子所示)输入是空格分隔的并且全部在一行上,那么您将需要:
$/ = " "在调用之前将记录分隔符设置为space()<>,或split将输入行解析为单独的值# read a line of input and extract 3 whitespace-separated values quadraticEq( split /\s+/, <>, 3 );
对于这样的问题,我几乎总是选择#2,但有多种方法可以做到这一点.