Perl Best Practices (excerpt)---04

Source: Internet
Author: User
Tags chop
Chapter 4: Values and Expressions
Data is lacking ...

A bit like a programmer.

— Arthur Norman Zero Three.

Use insert string delimiters only for strings that are actually inserted.

l Create a string literal and want to insert a variable, use double-quoted strings

my $ spam_name = "$ title $ first_name $ surname";

l Create a string literal and don't want to insert any variables, use single quoted strings

my $ spam_name = ‘DrLawrence Mwalle’;

l If the uninterpolated string itself contains single quotes, use q {…} instead:

my $ spam_name = q {r Lawrence (‘Larry’) Mwalle};

l Do not use backslashes (\) as quote delimiters; this only makes it difficult to distinguish content from containers:

my $ spam_name = ‘Dr Lawrence (\’ Larry \ ’) Mwalle’;

l If the uninserted string contains single quotes and unbalanced braces, use square brackets as delimiters instead:

my $ spam_name = q [Dr Lawrence] Larry {Mwalle};

Do not use "" or '' for empty strings.

       $ error_msg = q (); zero-three.

Don't write single-character strings in a visually ambiguous way. Zero Sanriku.

Use named characters for escaping. Do not use numeric escaping.

Via the use charnames directive (pragma)

       usecharnames qw (: full);

       $ escape_seq = "\ N {DELETE} \ N {ACKNOWLEDGE} \ N {CANCEL} Z"; 零三 柒.

Use named constants. Do not use use constants.

The sudden appearance of pure numbers in the middle of a program is often mysterious, often confusing, and a source of potential errors.

Replace this pure number directly with a read-only lexical variable, and use a variable noun to explain the meaning of the number:

       useReadonly;

       Readonlymy $ MOLYBDENUM_ATOMIC_NUMBER => 42;

       #Later ...

       print $ count * $ MOLYBDENUM_ATOMIC_NUMBER; zero three.

Do not substitute leading zeros for decimal digits.

If you must specify an octal value, use the built-in oct function, for example:

       useReadonly;

       Readonlymy% PERMISSIONS_FOR => (

              USER_ONLY => oct (600),

              NORMAL_ACCESS => oct (644),

              ALL_ACCESS => oct (666)

); Zero three.

Use underscores to improve readability of long numbers.

use bignum;

$ PI = 3.141592_653589_793238_462643_383279_502884_197169_399375;

$ subnet_mask = 0xFF_FF_FF_80; nothing.

Deploy multi-line strings on multiple lines.

If there are newline characters in the string, and the entire string cannot be lined up in one line, you should break after each newline character and concatenate those paragraphs:

       $ usage = “Usage: $ 0 <file> [-full] \ n”

                     . "(Use –full option for full dump) \ n"

                     ; Wanton one.

When a multi-line string exceeds two lines, heredoc (Here Document) is used.

For a few lines, the "break and reconnect after a new line" method is suitable, but for large paragraphs of text, it will start to become inefficient and ugly.

For multiline strings with more than two lines, use heredoc instead:

       $ usage = << "END_USAGE;

Usage:: $ 0 <file> [-full] [-o] [-beans] "

Options:

              -full: produce a full dump

              -o: dump in octal

              -beans: source is Java

       END_USAGE Indiscriminate.

When heredoc jeopardizes your indentation, use "theredoc" instead.

It is better practice to separate this type of heredoc into a predefined constant or subroutine ("theredoc"):

       useReadonly;

       Readonlymy $ USAGE => << ’END_USAGE’;

       Usage: qdump <file> [-full] [-o] [-beans] "

Options:

              -full: produce a full dump

              -o: dump in octal

              -beans: source is Java

       END_USAGE

       #Later ...

       if ($ usage_error) {

              warn $ USAGE;

       } Freedom.

Each heredoc stop sign is made into a single uppercase identifier with a standard prefix.

       print << ’END_LIST’;

       getname

       setsize

       putnext

       END_LIST wanton.

Termination symbols are quoted when heredoc is introduced.

Note that in the heredoc examples of the previous guidelines, use single or double quotes after <<.

Enclosing this marker in single quotes will force heredoc to not insert any variables.

Enclosing this marker in double quotes will ensure that the heredoc string is inserted into any variable. Indiscriminate.

Do not use barewords.

The strict directive checks for any unmodified characters during compilation:

       usestrict ‘subs’;

       [email protected] = map {sqrt $ _} 0..100;

       formy $ N (2, 3, 5, 8, 13, 21, 34, 55) {

              print $ sqrt [N], “\ n”;

       }

And then throw an exception:

       Bareword “N” not allowed while “strict subs” in use at sqrts.pl line 5

Reserved => for paired things.

Whenever you create a list of key-values and bright-values, use a "fat comma" (ie, =>, fat comma) to associate the keys with their corresponding values. For example, when building a hash:

       % default_service_record = (

              name => ‘<unknown>’,

              rank => ‘Recruit’,

              serial => undef

);

Don't use commas to sort statements.

Perl programmers with a C / C ++ background are used to writing C-style for loops in Perl programs:

# Binary search (binary chop) search ...

SEARCH:

       for ($ min = 0, $ max = $ # samples, $ found_target = 0; $ min <= $ max;) {

              $ pos = int (($ max + $ min) / 2);

              my $ test_val = $ samples [$ pos];

              if ($ target == $ test_val) {

                     $ found_target = 1;

                     lastSEARCH;

              }

              elsif ($ target <$ test_val) {

                     $ max = $ pos-1;

              }

              else {

                     $ min = $ pos + 1;

              }

       }

the correct one is:

# Binary search (binary chop) search ...

SEARCH:

       for (do {$ min = 0, $ max = $ # samples, $ found_target = 0;}; $ min <= $ max;) {

              # Same as before

       }

       print‘Sir ’,

              do {check_name ($ name); $ name;},

              ‘, KBE’;

Do not mix high and low priority Boolean operations.

To maximize the understanding of conditional testing, avoid and and not completely, and then reserve only low-priority or for error-prone built-in functions to specify "fallbackposition":

       open my $ source, ‘<’, $ source_file

              or croak “Could n’t access sourcecode: $ OS_ERROR”;

Each original list must be enclosed in parentheses.

       @ todo = (‘Patent concept of 1 and 0’, ‘Sue Microsoft and IBM’, ‘Profit!’);

Use table lookups to test membership in a list of strings;

Use any () to test membership of a list of anything else.

       #Index number has been taken away?

       if (any {$ requeste_slot == $ _} @allocated_slots) {

              print "Slot $ requested_slot is already taken. Please select another:";

              redoGET_SLOT;

}

If your list membership test uses eq, don't use any (), it's better to use a lookup table instead:

       Readonly my% IS_EXIT_WORD

              = map {($ _ => 1)} qw (

                            Qquit bye exit stop done last finish aurevoir

                     );

       Later ...

       if ($ IS_EXIT_WORD {$ cmd}) {

              abort_run ();

       }

Perl best practices (excerpt) --- 04
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.