CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
if statement in while loop

 



datlaravi
Deleted

Aug 10, 2000, 12:17 PM

Post #1 of 4 (409 views)
if statement in while loop Can't Post

Hi,
I was trying to open a file and print the contents based on the condition.
I am having a problem.
Please help me

$INPUT_FILE = "text.txt";
open(INPUT_FILE);
@array = <INPUT_FILE>;
close(INPUT_FILE);

foreach $key (@array) {

if ($key eq 'hello') {
print "hello\n";
}
else {
print "world\n";
}

}
It is printing the else condition.
The file contents are
hello
hello
hello
world
world
world


The program is printing world for all 5 lines

Thanks


Jasmine
Administrator / Moderator

Aug 10, 2000, 12:29 PM

Post #2 of 4 (409 views)
Re: if statement in while loop [In reply to] Can't Post

Don't forget to chomp the line -- remember, after each line in a file, there is a "newline" character. So in the file, the whole line isn't "hello", it's "hello\n";

Try using the following:
foreach $key (@array) {
chomp $key;
if ($key eq 'hello') {

The chomp will remove the newline character from the line of the file, changing "hello\n" to "hello", making your if ($key eq "hello") true.

Hope this helps.


DrZed
User

Aug 10, 2000, 12:59 PM

Post #3 of 4 (410 views)
Re: if statement in while loop [In reply to] Can't Post

$INPUT_FILE = "text.txt";
open(INPUT_FILE);

Ok, maybe this is some cool trick that I just don't know about, but does that combination actually work? It doesn't appear to be right.

Shouldn't you use:
$INPUT_FILE = "text.txt";
open(INPUT_FILE,$INPUT_FILE);

$INPUT_FILE (scalar) and INPUT_FILE (file handle) are two different variables. They are part of the same glob (I believe), but I wasn't aware that open would work that way.

I could easily be uninformed, so I would like to know.

Also, personally, I would use "<text.txt". I'm going to assume that reading is the default, but wouldn't it be better to clarify?

Dr. Zed


datlaravi
Deleted

Aug 10, 2000, 1:36 PM

Post #4 of 4 (410 views)
Re: if statement in while loop [In reply to] Can't Post

Thanks the help.
I used chomp $key and it worked

Hi DrZed,
It works just using the filehandle.
$INPUT_FILE = "text.txt";
open(INPUT_FILE);
I tried and it worked.

Thanks to both you.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives