[英]How to remove the content in the variable using perl
#! /usr/bin/perl
use warnings;
print "Please enter the number";
chomp($inNum =<>);
if($inNum =~ /^[0]+/)
{
print "The length is ",length($inNum),"\n";
print " Trailing Zero's present","\n";
$inNum =~ s/^[0]+/ /;
print "The new output is" , $inNum ,"\n";
print "The new length is ",length($inNum),"\n";
}
else
{
print "The input format vaild";
}
输出
请输入号码:000010
长度是:6
尾随零的礼物
新的输出是10
新的长度是:4
问题是新长度值应该为(2),但显示为(4)如何解决此问题?
您要s/^0+//
,而不是s/^[0]+/ /
。
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
print 'Please enter the number: ';
chomp(my $inNum = <>);
if ($inNum =~ /^0+/) { # has padding zeroes
printf "The length is <%d>.\n", length($inNum);
print "Padding zeroes present.\n";
$inNum =~ s/^0+/ /; # replace any padding zeroes with two spaces
printf "The new output is <%s>.\n", $inNum;
printf "The new length is <%d>.\n", length($inNum);
} else {
print "The input format was invalid.\n";
}
Please enter the number: 000010
The length is <6>.
Padding zeroes present.
The new output is < 10>.
The new length is <4>.
看起来您正在用2个空格字符替换四个0。 尝试这个。
$inNum =~ s/^[0]+//;
是的,您正在用空格替换,但是如果您不想更改reg表达式,也可以添加一个
sub trim($) { my $string = shift; $string =~ s/^\\s+//; $string =~ s/\\s+$//; return $string;
}
和使用
print "The new length is ",length(trim($inNum)),"\n";
如果您打算去除前导零,则可以考虑使用sprintf而不是正则表达式。
use feature qw(say);
use strict;
use warnings;
print "Please enter the number: ";
my $num = sprintf "%d", scalar <>;
say "$num";
请注意,如果您不输入数字,则会收到警告。
#!/usr/bin/perl
use strict;
use warnings;
print "Please enter the number";
my $num = 0 + <>;
print "The number is '$num'\n";
__END__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.