The final comma in Perl, the list

The items in the list in the Perl programming language are separated with the operator comma ,. Here is an example the code that creates the array which is 3 elements:

▶ Run
#!/usr/bin/perl

my @arr = ('one', 'two', 'three');

Perl, in contrast to, for example, the JSON allows you to specify a comma at the end of the list. This code creates a the same array as in the previous example:

▶ Run
#!/usr/bin/perl

my @arr = ('one', 'two', 'three',);

This array consists of three elements. The fact that in the end there is a decimal point has no effect. You would suggest that the presence of a comma at the end of the list add undef as the last value, but no, this is not happening. If there is a comma at the end of the list or not — it does not affect how Perl interpreterpath this list.

Recommendation

The Perl programming language anyway — is there in the list the final comma or not, but the program written not only to understand Perl, but in order to be understood by people. Therefore, there is the following recommendation, if you follow it, the code becomes a little easier to read and a bit easier to change.

Recommendation the following:

  • if the list is written to a string, the final comma should not
  • if each list item is written in a separate line, after the last element should be a comma

This recommendation follows that

  • if in the process list changes, used to be written in one line, and was recorded by the value in the string, then you need to add a trailing comma
  • and if a multiline list creates a list in one line, the final comma is necessary to remove

Here is an example of code which complied with this recommendation:

▶ Run
#!/usr/bin/perl

my @arr1 = ('one', 'two', 'three');

my @arr2 = (
    'one',
    'two',
    'three',
);

my %h = (
    a => 1,
    b => 2,
);

If list, each element of which is recorded in the line there is of course the comma and you need to add another element at the end of the list, then diff will consist of one remote line and two added:

diff --git a/script.pl b/script.pl
index 5634af0..eabe2f1 100644
--- a/script.pl
+++ b/script.pl
@@ -3,5 +3,6 @@
 my @arr = (
     'one',
     'two',
-    'three'
+    'three',
+    'four'
 );

If the recommendation is observed and at the end of this list is the final comma, the diff consists of one clear line:

diff --git a/script.pl b/script.pl
index 8575677..82b3adf 100644
--- a/script.pl
+++ b/script.pl
@@ -4,4 +4,5 @@ my @arr = (
     'one',
     'two',
     'three',
+    'four',
 );

Other articles

Comments