Reputation: 73
#! /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 ?
Upvotes: 1
Views: 273
Reputation: 3601
#!/usr/bin/perl
use strict;
use warnings;
print "Please enter the number";
my $num = 0 + <>;
print "The number is '$num'\n";
__END__
Upvotes: 0
Reputation: 67900
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.
Upvotes: 1
Reputation: 39158
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>.
Upvotes: 4
Reputation: 5470
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";
Upvotes: 2
Reputation: 2416
It looks like you're replacing the four 0s with 2 space characters. Try this.
$inNum =~ s/^[0]+//;
Upvotes: 3