in reply to String concatenation function
I find "box comments" to be a waste of time. The all-capitals also are harder to read than plain English... this looks like some old FORTRAN-66 code.############################### # STRING CONCAT FUNCTION # # BY DR JONATHAN REES # ###############################
You probably shouldn't assign to $1, $2, or so on. These special variables receive the results of regular expression captures. But maybe that's a lowercase 'ell' letter. You might avoid single letter variables too, especially ones that look like 0 O 1 l...$l = 5; # $l defines the number of asterisks
Pick your syntax: either &concat or concat(...). Combining them is redundant and may confuse someone maintaining your code.&concat($l); # calls the sub concat passing the # number of concatenations in $l
Also, don't describe the effect of every statement with a comment. Comments are not to explain what the statement does, they're to explain what the algorithm does. A year from now when you're very quick with Perl, the transliteral comments will just be distracting noise. Put strategy in comments, tactics in code.
Another example of transliteral comments. And where did $i come from? It would seem much more natural to have the function return a value and for the caller to catch the value in whatever variable they choose.print $i; # prints the result
And try to end your last printout with a newline. That's either the default value of $/, or a literal "\n".
Pick an indentation style that helps people read your code. If the closing curly brace was in column 1, people could see it was related to the sub statement.sub concat { ... }
Firstly, you seem to assume that $i will be empty when you call the function... what happens when you call this function twice?my $val = $_[0] + 1; for ($k = 1 ; $k < $val ; $k++){ $i = $i.$sym; }
Secondly, Perl numbers its arrays from zero, as you've discovered here. But you seem to think of iteration as starting with one. This isn't a crime, but you seem to have stumbled upon a loop strategy that gets you the right number of iterations, quite accidentally. Since the number in $k isn't useful to the loop, I'd suggest:
This leaves us with the following code (assuming there was no such 'abc' x 5 operation):my $i = ''; for (1 .. $_[0]) { $i = $i . $sym }
# Concatenate a number of symbols. print concat('abc', 5), $/; sub concat { my $i = ''; for (1 .. $_[1]) { $i = $i . $_[0] } return $i; }
--
[ e d @ h a l l e y . c c ]
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: String concatenation function
by Juerd (Abbot) on Jun 02, 2003 at 05:20 UTC | |
by jonnyr9 (Initiate) on Jun 10, 2003 at 09:32 UTC |