The code my $str = <STDIN>; graps "snape\n" - it includes the newline. That's the extra character. It's often helpful to print out your string, but do so in a way that shows hidden whitespace. I usually do it like this: print "str = [$str]\n"; - this puts brackets around it so that I can see if there are spaces or newlines at the end.

If I add chomp after the input for $str, I'm not getting any problem - I think you might be calling it as $str = chomp $str which is wrong. Just call chomp $str; like this:

#!/usr/bin/perl -w use strict; use warnings; print "Enter the string ="; my $str = <STDIN>; chomp $str; #### here is the call to chomp print "Enter the size ="; my $n = <STDIN>; print "The Length of the string = ",length($str); if ($n <= length($str)){ my $x = pretty_print($str,$n); print "\nThe substring is = ",$x; } else{ print"\nThe length of the string is shorter than the size "; } sub pretty_print{ my ($dna,$len) = @_; my $substring = substr($dna,0,$len); return $substring; }
So close :-)


In reply to Re: Length and Chomp ?? by Tanktalus
in thread Length and Chomp ?? by snape

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.