LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 837|回复: 4

Perl 用if循环如何比较文字呢?

[复制链接]
发表于 2005-7-11 14:19:10 | 显示全部楼层 |阅读模式
#! /usr/bin/perl -w
print "Enter the Butten where did you what to transfer C or F : \n";
chomp($e=<STDIN>);
$b="C";
if ($e=$b) {
print "Enter the C temp :  \n";
chomp($c=<STDIN>);
$f=(9/5)*$c+32;
print "The F temp is $f  F \n";
} else {
print "The F temp is: \n";
chomp($f=<STDIN>);
$c=($f-32)/(9/5);
print "The C temp is $c C. \n";
}

这样现在不对,哪怕输入F也是提示输入摄氏度,应该输入F就输入华氏的才对。

[root@eddie eddie]# ./temper
Enter the Butten where did you what to transfer C or F :
F
Enter the C temp :
34
The F temp is 93.2  F
 楼主| 发表于 2005-7-11 15:07:13 | 显示全部楼层
搞好了,不容易。总算找到等于的表达方式了
#! /usr/bin/perl -w
print "Enter the Butten where did you what to transfer C or F : \n";
chomp($e=<STDIN>);
#$b="C";
if ($e=~C) {
print "Enter the C temp :  \n";
chomp($c=<STDIN>);
$f=(9/5)*$c+32;
print "The F temp is $f  F \n";
}
elsif ($e=~F) {
print "The F temp is: \n";
chomp($f=<STDIN>);
$c=($f-32)/(9/5);
print "The C temp is $c C. \n";
}
else {
print "You input a wrong string ! \n";
}
回复 支持 反对

使用道具 举报

发表于 2005-7-11 19:04:32 | 显示全部楼层
不对。

字符串==用  eq。
那个=~是正则表达式的match,即匹配。

字符串比较:
eq : equality
ne :  inequality
lt : less than
gt : greater than
le : less than or equal
ge  :greater than or equal

正则表达式
=~ :match
!~   : unmatch
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-7-12 09:13:55 | 显示全部楼层
可是用那个也能成啊。。。
回复 支持 反对

使用道具 举报

发表于 2005-7-12 09:17:20 | 显示全部楼层

  1. print "===================================\n";

  2. print "y or n ?\n";
  3. $ch = getc(STDIN);
  4. print "you selected :", $ch, "\n";

  5. $ch = <STDIN>;   # skip the last input line

  6. print "input a line: ";
  7. $str = <STDIN>;
  8. print "the first char is: ", chr(ord($str)), "\n";
  9. if (ord('y') == ord($str)) {
  10.         print "yes\n";
  11. } else {
  12.         print "no\n";
  13. }

  14. print "input: ";
  15. $data = "";
  16. read(STDIN, $data, 1);
  17. print "read: \[$data\]\n";
  18. if ('y' == $data) { print "yes\n"; }
  19. else {print "no\n";}
复制代码


===================================
y or n ?
y
you selected :y
input a line: yes
the first char is: y
yes
input: y
read: [y]
yes


这段代码必须要每次输入回车才能继续,如果想
实现单击一个键不需要回车,可参考perlfunc中
的getc的说明。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表