Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
In recent days many of our meditations around the monastery concerned some deeply involved issues such as this, or this, or that other thing over there. These and many others are certainly quite healthy discussions and deserve the credit they in fact already got. However, there has been little attention given to the subtle intricacies of performing daily Perl hacking routines. In this thread, I would like to draw your attention and, of course, pursue a constructive consultation on the sometimes overlooked and at the first glance trivial subject of variable naming.

Certainly, many of you would shout and even point me in the direction of one of these exceptional threads:



And that’s about all we have that is at least remotely related to this subject.

. . . vladb shuffles his old ‘Code Complete’ book a couple pages . . .

Ahh, here I found it, quote:

“You can’t give a variable a name the way you give a dog a name – because it’s cute or it has good sound. Unlike the dog and its name, which are different entities, a variable and a variable’s name are essentially the same thing. When it comes to variable naming conventions, a couple obvious rules spring to mind:
  • Fear short variables, unless used once and close to where they are declared (such as in a for loop).

    This is way beyond evil:
    my (@a, @b); # . . . # initialize variables # . . . my @m = map { my $x = $_; grep { /^$x$/ } @b; } @a; print @m;
    What are these variables there? Yes, yes, the @a and @b variables? And what would I like to know is exactly @m for? These questions are cleared by simply renaming the variables:
    my (@registered_users, @personalized_users); # . . . # initialize variables # . . . my @advanced_users = map { my $registered_user = $_; grep { /^$registered_user$/ } @personalized_users; } @registered_users;
    By simply naming the variables right, we have also implicitly added some good piece of in-line documentation. Observing the code, it becomes crystal clear that its purpose is to gather all users that are both personalized and registered (say, with a portal). These users are classified as being ‘advanced’ in that they have not only registered with the portal, but also personalized certain aspects of it.

  • A variable must exist to serve only one purpose.

    I had a couple scripts where I would declare a multi-purpose variable such as $temp or $buffer and use them for various different purposes throughout the code. This only led to a number of bugs that was hard to locate and fix. Therefore, it’s best to avoid using ‘generic’ variables. It is best to be specific in variable naming. A variable name should stand for what the variable’s purpose in the code is. Of course, it’s hard to come up with a suitable name when a variable’s purpose in life hasn’t been clearly defined ;-).

  • Stick to a single naming convention agreed upon by your fellow developers.

    This is very much self-explanatory. Being on the same page in terms of naming conventions serves good when it comes your time to expropriate, debug, or review someone else’s code (say, another developer in your company).


There’s certainly more to this list, but let me direct your attention to at least a few naming conventions specific to Perl. In addition to the ones mentioned above, throughout my short career as a Perl hacker, I have observed other developers follow this guidelines:
  • Use meaningful prefixes/suffixes to signify the data type of a variable.

    Unlike other languages, in Perl every variable that is other than a scalar reference has one of these prefixes: @, $, %. For example,
    my @employees; # declare an array. my %records; # declare a hash variable. my $name; # declare a scalar
    However, things become a little bit more confusing when it comes to scalar references in Perl. Similarly to the way it is being done in other languages such as C and Pascal, a number of Perl hackers choose to use suffixes that signify that type of a structure that a scalar reference is pointing to. Here’s a sample,
    # reference to an array my @employees; my $employees_aref = \@employees; # reference to a hash my %records; my $records_href = \%records. # reference to a scalar my $huge_text; my $huge_text_sref = \$huge_text; # This naming is popular in subroutine parameters. sub calc_employee_salary { my ($employee_aref) = @_; # $employee_aref is a reference to an array # holding employee IDs (or names, whichever) # since this is an array reference, use ‘@’ to get to the # actual array. foreach (@$employee_aref) { # . . . } }
  • Private class subroutines should be prefixed with ‘_’ (underscore).

    A quote from perltoot explains it all:

    Perl doesn't impose restrictions on who gets to use which methods. The public-versus-private distinction is by convention, not syntax. (Well, unless you use the Alias module described below in Data Members as Variables.) Occasionally you'll see method names beginning or ending with an underscore or two. This marking is a convention indicating that the methods are private to that class alone and sometimes to its closest acquaintances, its immediate subclasses. But this distinction is not enforced by Perl itself. It's up to the programmer to behave.


There are certainly hundreds more examples of indecent variable naming. I hereby challenge you to step forward and share your wisdom! ;-)

_____________________
$"=q;grep;;$,=q"grep";for(`find . -name ".saves*~"`){s;$/;;;/(.*-(\d+) +-.*)$/; $_=<a HREF="/index.pl?node=%22ps%20-e%20-o%20pid%20"> "," $2 </a>;`@$_ +`?{print"+ $1"}:{print"- $1"}&&`rm $1`; print$\;}

In reply to Of variable {mice} and its name {man}. by vladb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-20 14:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found