in reply to Nested While loop not working
G'day Manisha,
Welcome to the monastery.
I created two files:
$ cat ABC qwe asd zxc $ cat CDE rty fgh vbn
I ran your code like this (apart from the shebang and three use lines, it's a copy of what you posted):
#!/usr/bin/env perl use strict; use warnings; use autodie; open(file_one,"ABC"); while(my $line = <file_one>) { open(file_two,"CDE"); while(my $line2=<file_two>) { print "line : $line line2 : $line2 \n"; } close(file_two); }
I got a warning but then output from both files, like this:
Name "main::file_one" used only once: possible typo at ./pm_example.pl + line 8. line : qwe line2 : rty line : qwe line2 : fgh line : qwe line2 : vbn line : asd line2 : rty line : asd line2 : fgh line : asd line2 : vbn line : zxc line2 : rty line : zxc line2 : fgh line : zxc line2 : vbn
So, check the filenames, file permissions and file contents. If you ask for diagnostic messages, you'll usually get useful information: see Pragmas for documentation on those that I used; while you're learning, diagnostics can also be useful but don't leave it in production code.
Here's a better way to write it:
#!/usr/bin/env perl use strict; use warnings; use autodie; open my $fh1, '<', 'ABC'; while (defined(my $line1 = <$fh1>)) { chomp $line1; open my $fh2, '<', 'CDE'; while (defined(my $line2 = <$fh2>)) { chomp $line2; print "line1 : $line1 line2 : $line2\n"; } }
Now the output has no warnings and all those extra newlines are gone:
line1 : qwe line2 : rty line1 : qwe line2 : fgh line1 : qwe line2 : vbn line1 : asd line2 : rty line1 : asd line2 : fgh line1 : asd line2 : vbn line1 : zxc line2 : rty line1 : zxc line2 : fgh line1 : zxc line2 : vbn
See the following for information on what I did differently to your posted code: chomp; defined; and open. Also, the following have useful information regarding while loops: "perlsyn: Loop Control" and "perlop: I/O Operators". Finally, if you've only just started to learn Perl, I recommend you first read all of "perlintro -- a brief introduction and overview of Perl".
-- Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Nested While loop not working
by Manisha (Initiate) on Mar 11, 2014 at 10:33 UTC | |
by kcott (Archbishop) on Mar 12, 2014 at 06:49 UTC | |
by Anonymous Monk on Mar 12, 2014 at 09:34 UTC | |
by Manisha (Initiate) on Mar 12, 2014 at 09:37 UTC |