Re: [NEWBIE] Trivial?



On 09/29/2007 12:39 AM, El Bandolero wrote:
I'm solving an exercise studying on a tutorial

The task is to print the (empty or not) lines of a file numbering only the non empty ones.

How the h### is possible that the following code gives the same result if I change line 9 with the opposite condition?
if (!$lines[$i]=="")

1 #!/usr/bin/perl
2 #

Put this line near the top of your program:

use warnings;


3 $file = 'C:\Perl\html\Artistic.txt'; 4 open(PIP, $file); 5 @lines = <PIP>; 6 close(PIP); 7 for ($i=0;$i <= @lines;++$i)
8 {
9 if ($lines[$i]=="")
10 {print $i." ".$lines[$i]};
11 }



The two problems with your program are (1) string comparisons are done with 'eq' not '==' and (2) un-chomped blank lines have a single \n character in them.

This comparison should work better:

if ($lines[$i] ne "\n")

That line alone won't complete the execise. Depending upon the exercise requirements, you may also need another counter ($j). I'll let you figure out if that's the case.

.



Relevant Pages

  • Re: [NEWBIE] Trivial?
    ... The task is to print the (empty or not) lines of a file numbering only the ... You should enable warnings and perl would have informed you that you are using numerical comparison on strings instead of numbers. ...
    (comp.lang.perl.misc)
  • Re: Trivial?
    ... non empty ones. ... change line 9 with the opposite condition? ... use warnings; ... The two problems with your program are string comparisons are done ...
    (comp.lang.perl.misc)
  • Re: Trivial?
    ... >>> I'm solving an exercise studying on a tutorial ... >> numbering only the> non empty ones. ... lines of a file numbering only the non empty ones." ...
    (comp.lang.perl.misc)
  • Re: Trivial?
    ... >>> I'm solving an exercise studying on a tutorial ... >> numbering only the> non empty ones. ... lines of a file numbering only the non empty ones." ...
    (comp.lang.perl.misc)
  • [NEWBIE] Trivial?
    ... I'm solving an exercise studying on a tutorial ... The task is to print the (empty or not) lines of a file numbering only the ...
    (comp.lang.perl.misc)