kanewilliam7777 has asked for the wisdom of the Perl Monks concerning the following question:

my $param_value='123456789'; if(length($param_value)!=10) { print 'Fail'; } else { print 'Success'; }

Needed & correct result is "Fail". but it's return "Success".

Please let me know how to check the string length

Replies are listed 'Best First'.
Re: Perl length if condition not working
by Eily (Monsignor) on Sep 25, 2018 at 10:18 UTC

    Your script does print Fail. But my guess is that rather than get '123456789' from the code you get it from STDIN (something like $param_value = <>;) which would mean there is a \n character at the end. You can solve this like that:

    chomp($param_value);

    If that's not your issue, you'll have to show us code where the problem is actually present. See How do I post a question effectively?.

    Edit: you would be able to see the extra char with either of these:

    use Data::Dumper; $Data::Dumper::Useqq = 1; ... print Dumper $param_value;
    or
    use Data::Dump "pp"; ... pp $param_value;
    I personally prefer Data::Dump, but Data::Dumper should already be installed on your machine.

Re: Perl length if condition not working
by Your Mother (Archbishop) on Sep 25, 2018 at 10:18 UTC

    Fails, appropriately, for me. Are you sure that’s the code you’re running? Chomp issue? Try adding this–

    printf "[%s] -> %d\n", $param_value, length $param_value; # [123456789] -> 9
Re: Perl length if condition not working
by hippo (Archbishop) on Sep 25, 2018 at 10:30 UTC

    Top tip: if you use Test::More your tests will automatically tell you how the condition fails. eg:

    use strict; use warnings; use Test::More tests => 1; my $param_value='123456789'; is (length($param_value), 5, 'Length of $param_value') or diag "\$param_value = >$param_value<";

    See How to ask better questions using Test::More and sample data and SSCCE for further hints.

    PS. In case it wasn't clear, I've changed the expected length to 5 so the test deliberately fails. Testing against an expected length of 9 would succeed, of course.