Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

How to find empty in empty

by Anonymous Monk
on Nov 19, 2002 at 07:12 UTC ( [id://214043]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, problem I have been having is following, I know solution is there but I cant seem to get there.... I am reading by user defined file, which looks like:
jan 2.76 feb 3.20 mar 1.6 apr 4.00
In the user file there might be empty lines which I wish to ignore, I would like to know how many lines actually have text on.......one of several versions of code attempts
$empty[0] =""; open (VER,$f_name); while (defined ($rows = <VER>)) { chomp($rows); ($rows1,$rows2)=split(/\ /,$rows); $names[$l]=$rows1; $versions[$l]=$rows2; if ($names[$l] != $empty[0] ) #HOW should this be done??? { $l++; } } close VER;
How to compare if the line is empty so that $l does not increase in case of empty table member.... BR Hewarn

Replies are listed 'Best First'.
Re: How to find empty in empty
by grep (Monsignor) on Nov 19, 2002 at 07:20 UTC
    use next inside your loop to skip the blanks. next will skip the current iteration and move on to the next for any loop structure.
    while (defined ($rows = <VER>)) { chomp($rows); next if ($rows eq ''); # this'll skip blank lines ($rows1,$rows2)=split(/\ /,$rows); $names[$l]=$rows1; $versions[$l]=$rows2; }


    grep
    Mynd you, mønk bites Kan be pretti nasti...
Re: How to find empty in empty
by Monky Python (Scribe) on Nov 19, 2002 at 07:58 UTC
    Hi, some remarks:
    - use "use strict"
    - initialize your data before using it ($l is not initialized)
    - you don't need rows, row1, row2 as temporary variables

    The following script checks for an empty line with the
    mighty regexp /^[\s]+$/ instead of
    comparing with "".

    #!/usr/local/bin/perl -w use strict; my (@names, @versions,$l,$e); $l=0; $e=0; while (<DATA>) { chomp; if (! /^[\s]+$/) { ($names[$l],$versions[$l])=split(/[\s]+/); $l++; } else { $e++; } } $,=", "; print "@names @versions\n"; print "empty lines=$e\n"; __DATA__ jan 2.76 feb 3.20 mar 1.6 apr 4.00
      Um, '+' means at least one (and you don't need the box): ! /^\s*$/ Anyway, it's even easier just to check for a non-space: /\S/ But, as long as we're at it, why not accept only well-formed lines:
      if ( /^(\w+)\s+([\d.]+)/ ) { ($names[$l],$versions[$l])=($1,$2); ++$l; else { . . .

        p

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://214043]
Approved by grep
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-19 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found