Seitenanfang

Perl style and C style

Dieser Post wurde aus meiner alten WordPress-Installation importiert. Sollte es Darstellungsprobleme, falsche Links oder fehlende Bilder geben, bitte einfach hier einen Kommentar hinterlassen. Danke.


Perl is TIMTOWTDI but not every style is good style. It allows you to write down source which isn't executed the way you think.

I stumbled into a piece of code earlier today (which doing something completely different in this file):

my ($i, $j, $cur, $next);for $i (0 .. $#A) {	$cur = $i + 1 if $i > 0;	for $j (0 .. $#B) {		$next = _someotherfunction($W[$j + 1], $cur + 1, ($A[$i] ne $B[$j]) + $W[$j]);		$W[$j] = $cur;		$cur = $next;	}}return $next;
It's working, but there are some issues:

Pre-defining variables is C style

Some other languages also require variables to be defined at the beginning of a scope, but Perl doesn't. Doing so results in some major drawbacks. $next is the only variable used outside the $i loop and it's the only one which has to be defined outside the loop. $cur wasts memory because it lives during every source piece which might be added later between the end of the $i loop and the return statement. A simple integer doesn't waste that many memory but I fixed a similar issue earlier today. Limiting variables to their usage scope and re-arranging some source parts reduced the script's memory usage from about 750 to 115 MB.

Survival of loop variables

$i and $j don't waste memory, their situation is quite worse. Given $#A is 3 and $#B is 2, what output would you expect from a print "i=$i, j=$j"; just before the return statement? It should be i=3, j=2 but it's i=, j=. Adding the same print as the last statement into $j's loop shows the expected line (as last output line), but where do the values get lost within two closing loops?

Every for-loop variable is always used with an implicit "my" who limits the variables scope to the loop. Pre-defining them creates two different variables sharing the same name:

my $i;for $i (1..10) { print $i; }print $i;
The red lines are using the first variable named $i, but the blue line is using a completely new variable (also named $i). It's very strongly suggested to write for my $i to show everybody that $i is limited in it's scope. You can't choose if the variable's scope should be limited to the for loop but only decide if you want your code to look like what it is actually doing.
 

Noch keine Kommentare. Schreib was dazu

Schreib was dazu

Die folgenden HTML-Tags sind erlaubt:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>