Click to See Complete Forum and Search --> : Variable Problem


edatz
07-19-2010, 01:36 PM
I have a script which I use to access some files. The first step of the processs is to enter a word in a form, which then passes me to the file.

words.txt (the file with the words in)
pizza
beer

open (AWDF,"words.txt");
$first = <AWDF>;
close (AWDF);
$theword = "$first";

print "$theword"; # ----- works fine

The print shows the first word in the file like it should. It even passes to other parts of the script and can be printed (for testing).

However, when I use word in a form to do the first step in the process of the script - it does not work.

But it will if the variable is like this!
$theword = "pizza";
...and everything works properly.

I don't understand why the variable will work one way, but not the other. What have I done wrong?

Any ideas?

edatz
07-19-2010, 03:15 PM
I think I've just solved it.

open (AWDF,"words.txt");
$first = <AWDF>;
close (AWDF);
chomp($first);
$theword = "$first";

It appears that reading the file like this produced some whitespace that I was unaware of. A chomp was inserted and the script now works. I can enter my word and go to the next process okay. :D

sohguanh
07-19-2010, 10:18 PM
I think I've just solved it.

open (AWDF,"words.txt");
$first = <AWDF>;
close (AWDF);
chomp($first);
$theword = "$first";

It appears that reading the file like this produced some whitespace that I was unaware of. A chomp was inserted and the script now works. I can enter my word and go to the next process okay. :D

In general, Perl process text file assuming newline is the record separator. It has been debated why the default file input operator left the newline in the variable. There are developers who demand Perl take default action to remove the newline and there are developers who say put the whole line including the newline in and let them decide what to do with it. My experience is usually I don't need the newline at the end.

chomp function will remove the last character if it is newline. chop function will just blindly remove the last character regardless if it is newline or not.

edatz
07-20-2010, 01:57 AM
My experience is usually I don't need the newline at the end.
Mine too. Though there are times it's handy, but I'd rather code that in, instead of wondering if Perl is goning to leave it there or not (sometimes it doesn't appear to happen).

In this case each word is a whole record and I read the first line only. The file gets rotated daily (ish). My rotation code is a simple thing that has an SSI on each HTML page (where needed) so that the first hit to the site kicks in the rotation. I do this instead of a CRON Job, so it only actions when needed.