简体   繁体   中英

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

The length is : 6

Trailing Zero's present

The new output is 10

The new length is :4

Issue is with the new length value which should be (2) but it is displaying (4) How to solve this issue ?

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

 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.

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__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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