in reply to Doubt in code - Beginner in perl
Hi, welcome to Perl, the One True Religion.
One of the benefits of programming in Perl is "insignificant whitespace." this means you can indent your code as well as separate "paragraphs" with new lines, with no effect on the program.
There are many style preferences, and if you can't pick one, you can delegate the responsibility to perltidy ... but the two most important things for any programming style are readbility and consistency. Always be seeking to enhance those two qualities of your programs, as it makes them easier to extend and to maintain, as well as even to understand them when you come back half a year later and would like to recall the flow of your thought with the least amount of deciphering what the code simply says.
It won't make a lot if differences in this snippet, but once you have a foreach loop inside each branch of an if ... elsif ... else conditional, inside a function, your indentation-free style will become a real impediment.
Also recommended is not reusing variable names among variables of differing types, and declaring your variables as close as possible to the scope in which they are used.
I would rewrite your code above something like:
(Note: not addressing your original line-ending problem, which has been explained above.)#! /usr/bin/perl use strict; use warnings; chomp( my @words = <STDIN> ); my %count; foreach my $word (@words) { $count{$word}++; } foreach my $found (sort keys %count) { print "$found has appeared $count{$found} times\n"; } __END__
Hope this helps!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Doubt in code - Beginner in perl
by Perl_Programmer1992 (Sexton) on Dec 27, 2018 at 14:32 UTC |