...
This noncompliant example first provides a constant value $BufferSize, set to 512. This constant can later be used to buffer data read in from a file. But then the code example defeats the purpose of defining $BufferSize as a constant by assuming its value in the subsequent expression:
| Code Block | ||||
|---|---|---|---|---|
| ||||
our $BufferSize = 512;
# ...
my $nblocks = 1 + (($nbytes - 1) >> 9); # because $BufferSize = 512 = 2^9
|
The programmer 's assumption underlying this code is that "might assume that everyone knows that $BufferSize equals 512 ," and that right-shifting 9 bits is the same (for positive numbers) as dividing by 512. However, But if $BufferSize changes to 1024 on some systems, the subsequent expression must also be updated and can be overlooked easily. This makes modifications of constants difficult and error prone.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
my $nblocks = 1 + (($nbytes - 1) / $BufferSize;
|
...
Tool | Diagnostic |
|---|---|
Perl::Critic | ValuesAndExpressions::ProhibitMagicNumbers |
Related Guidelines
...
...
...
...
Bibliography
...
...
| [ |
|---|
...
...
...
/]. [ProhibitMagicNumbers|http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/ValuesAndExpressions/ProhibitMagicNumbers.pm]. \[[Wall 2011|AA. Bibliography#Manpages]\] [perlfunc|http://perldoc.perl.org/perlfunc.html]EXP06-C. Operands to the sizeof operator should not contain side effects 03. Expressions (EXP) EXP08-C. Ensure pointer arithmetic is used correctly