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

I'm a novice, and I'm having a problem making a chomp loop. When people fill out my form textfield, they hit the enter key several times, making it necessary to chomp the variable for that field. In the code below I am able to chomp the variable one time, but if they hit enter more than once, more newlines make more spaces in the text file. Could someone please give me a chomp loop that will eliminate all newlines before i store the variables in a text file? Please don't make it heavy. I'm a novice, and easily confused. Thank you very much for your help!
chomp ($message); open (ENTRY, ">>guestbook2.txt") ||ErrorMessage; flock(ENTRY, 2); print ENTRY "$name|$email|$url|$location|$message|$thisday $thismonth $mday, $thisyear\n"; flock(ENTRY, 8); close (ENTRY);

Replies are listed 'Best First'.
Re: They keep hittin the enter key.
by dws (Chancellor) on Feb 11, 2003 at 05:21 UTC
    Could someone please give me a chomp loop that will eliminate all newlines before i store the variables in a text file?

    Assuming you are really interested in deleting trailing newlines,

    $message =~ s/[\r\n]+$//;
    will nuke them. With data that comes from textarea fields, you have to worry about both carriage returns and linefeeds, unless you first do something like
    $message =~ s/\r//g;
    to remove the hard returns, leaving you with Unix-friendly strings.

Re: They keep hittin the enter key.
by n4mation (Acolyte) on Feb 11, 2003 at 05:55 UTC
    YES! IT WORKED! THANK YOU VERY MUCH! If you have time could you explain that to me?

      Basically, $message =~ s/[\r\n]+$//; does a substitution on the string $message, replacing one or more ([...]+) characters in the given class ([\r\n], the escape sequences for carriage return and line feed), as long as they're right before the end of the string ($). That's a really bare explanation of the regular expression; see perlrequick and perlretut for more detail.

      Regular expressions are one of Perl's sharpest tools: they can help you get a lot of work done in a hurry, but they aren't easy to use. Spending some time learning about them would be a good idea, but don't get discouraged if you don't "get it" right away.

      --
      F o x t r o t U n i f o r m
      Found a typo in this node? /msg me
      The hell with paco, vote for Erudil!

      You might also want to check out this tutorial. It's a great intorduction to regexps from Simon Cozen's book, Beginning Perl, Wrox Press. Matter of fact, you'll probably want to read the whole book here. It's a great gentle introduction to most of Perl.