简体   繁体   English

如何使用Perl删除变量中的内容

[英]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";
 }

output 输出

Please enter the number :000010 请输入号码:000010

The length is : 6 长度是:6

Trailing Zero's present 尾随零的礼物

The new output is 10 新的输出是10

The new length is :4 新的长度是:4

Issue is with the new length value which should be (2) but it is displaying (4) How to solve this issue ? 问题是新长度值应该为(2),但显示为(4)如何解决此问题?

You want s/^0+// , not s/^[0]+/ / . 您要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>.

It looks like you're replacing the four 0s with 2 space characters. 看起来您正在用2个空格字符替换四个0。 Try this. 尝试这个。

$inNum =~ s/^[0]+//; 

yea you are replacing with white spaces, still if you dont want to change your reg expressions you could add a sub 是的,您正在用空格替换,但是如果您不想更改reg表达式,也可以添加一个

 sub trim($) { my $string = shift; $string =~ s/^\\s+//; $string =~ s/\\s+$//; return $string; 

} }

and use 和使用

print "The new length is ",length(trim($inNum)),"\n";

If your intention is to strip leading zeros, you might consider using sprintf instead of a regex. 如果您打算去除前导零,则可以考虑使用sprintf而不是正则表达式。

use feature qw(say);
use strict;
use warnings;

print "Please enter the number: ";
my $num = sprintf "%d", scalar <>;
say "$num";

Be aware that if you do not enter a number, you will get a warning. 请注意,如果您不输入数字,则会收到警告。

#!/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM