Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: What is the difference?

by Thelonius (Priest)
on Apr 08, 2003 at 14:45 UTC ( [id://248950]=note: print w/replies, xml ) Need Help??


in reply to What is the difference?

You'll get different counts on lines that have leading white space. The second program will count an empty field at the beginning of the line. The correct way to do this program is:
#!/bin/perl -w my $line = 0 while (<>) { chomp; $line += tr/ \t/./c; } print $line, "\n";
or
#!/bin/perl -w my $line = 0 while (<>) { $line += tr/ \t\r\n/c; } print $line, "\n";

Replies are listed 'Best First'.
Re: Re: What is the difference?
by YAFZ (Pilgrim) on Apr 08, 2003 at 15:05 UTC
    Thanks for enlightening me! ;-) I prefer your second example. The only problem with that example is that you've forgotten one single slash character at the end of tr:
    $line += tr/ \t\r\n/c;
    which must be:
    $line += tr/ \t\r\n//c;
    After fixing that, the sript works cool ;-)

    I also realized that I can handle the situation using the command line:
    $ tr [:space:] -d <ccount.pl | wc 0 1 69
    Now I think that tr (in Perl or in shell) is a better way to get rid of unwanted characters, am I wrong?

    P.S.: If Thelonious S. Monk programmed (in any language) woe to the ones who could maintain his code ;-)

      Your tr (the program) example does, indeed, get rid of non-whitespace. The Perl program, howver, does not. What it does is: take all characters but some whitespace (those with ASCII codings 32, 9, 13, 10, in order), changing them with themselves, and returning how many have been (non) changed.

      The /c option complements the first list of tr///, while leaving the second list empty makes it equal to the first (in this case, the complemented first). tr/// in any case returns the number of characters interested by the transliteration.

      -- 
              dakkar - Mobilis in mobile
      

      Most of my code is tested...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-25 16:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found