chomp函数基础示例与问题解析
示例代码展示了基础的输入读取与重复打印逻辑: 复制代码 代码如下: #!/bin/perl print "Please input an string and a number by order!\n"; $the_string=<>; $the_numb=<>; print "The result is \n"; print "$the_string"x"$the_numb";
执行上述代码后的输出结果如下: The result is my my my my my
出现上述问题的原因在于未使用 chomp 函数处理输入数据。
接下来观察加入 chomp 函数后的情况:
修改后的代码如下: 复制代码 代码如下: #!/bin/perl print "Please input an string and a number by order!\n"; chomp($the_string=<>); chomp($the_numb=<>); print "The result is \n"; print "$the_string"x"$the_numb";
修正后的运行结果为: The result is mymymymymy
若字符串末尾包含换行符,chomp 可将其移除。这几乎是该函数的全部功能,例如: $text = “a line of text/n”; #也可由输入获得 chomp($text); #移除换行符(/n)。 此功能极具实用价值,几乎每个 Perl 程序都会用到。它是移除字符串末尾换行符的最佳方式。基于 Perl 的一条基本原则:在需要变量的地方,可用赋值表达式替代。Perl 先执行赋值再使用变量,因此最常用的写法为: chomp ($text = ); #读取但不含换行符
$text = ; chomp ($text); #效果相同,但分两步完成
初看第一种组合写法较复杂,若视为读入后 chomp 两步操作,分开写更自然;若视为读取不含换行符的一行,合并写更恰当。鉴于大多数 Perl 程序员采用第一种写法,建议跟随这一习惯。 chomp 是一个函数,其返回值为移除的字符个数。该数值通常用处不大: $food = ; $betty = chomp $food; #得到值1 使用 chomp 时可加或不加括号 (),这是 Perl 的通用规则:除非省略括号会改变含义,否则可省略。 若末尾有两个及以上换行符,chomp 仅移除一个;若无换行符,则不做任何操作并返回 0。
chop 和 chomp 函数的区别
chop 函数负责删除标量变量的最后一个字符或数组中每个元素的最后一个字符,并返回修改后的值。chop 常用于删除来自 STDIN、文件或命令置换结果的输入行末尾的换行符。 chomp 函数负责删除标量变量或数组元素中的最后一个字符,但仅在该字符为换行符时才执行删除,并返回删除的字符数目。使用 chomp 替代 chop 可避免误删非换行符的其他字符。 例1:chop #!/usr/bin/perl $v = 'Flowers'; $r = chop($v); print "$v (without $r)\n"; 运行结果 [root@localhost per]# ./1-16.pl Flower (without s) 例2:chomp #!/usr/bin/perl print "User name: "; $name = < STDIN >; chomp $name; print "Your user name is : $name\n"; 运行结果 [root@localhost per]# ./1-18.pl User name: Bill Your user name is : Bill