On Thu, 2002-04-04 at 15:01, Bruce Ambraal wrote: > Hi all > > My code below does the following : > - Reads from STDIN > - Splits the input on whitespace > - And prints the frequency of terms, with each term printed next to its frequency on >STDOUT. > > I need another approach (code) to do the same things > > <snip />
What sort of approach? This seems to be the optimal (I would even say canonical) solution to the find-the-frequency-of-words-in-a-stream problem. > if( exists $freq{$w} ){ > $freq{$w}++; > }else{ > $freq{$w} = 1; > } <snip /> This if is not necessary. The '++' operator does not complain about the presence of undef (it just treats it like 0) and hash have autovivification (the spring into life when you use them). So you can say $freq{$w}++; here instead. The only other simple solution is the same algorithm with less code: <example> #!/usr/bin/perl -lan $freq{$_}++ for @F; END { print "$_ occured $freq{$_} times" for keys %freq } </example> -n causes Perl to assume the following loop around your program, which makes it iterate over filename argu ments somewhat like sed -n or awk: LINE: while (<>) { ... # your program goes here } -l[octnum] enables automatic line-ending processing. It has two separate effects. First, it automatically chomps "$/" (the input record separator) when used with -n or -p. Second, it assigns "$\" (the output record separator) to have the value of octnum so that any print statements will have that separator added back on. If octnum is omitted, sets "$\" to the current value of "$/". -a turns on autosplit mode when used with a -n or -p. An implicit split command to the @F array is done as the first thing inside the implicit while loop pro duced by the -n or -p The only other trick here is the use of the END block to that is executed at the end of the program (after the last normal statement is reached or the program exits due to a return or exit). -- Today is Prickle-Prickle the 21st day of Discord in the YOLD 3168 Wibble. Missile Address: 33:48:3.521N 84:23:34.786W -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]