develooper Front page | perl.perl5.porters | Postings from August 2009

Re: [DOC] Modernization: perldata

Thread Previous | Thread Next
From:
Flavio Poletti
Date:
August 29, 2009 23:29
Subject:
Re: [DOC] Modernization: perldata
Message ID:
aeba50980908292328y1dd9edfbi9e11a8808005ce06@mail.gmail.com
Hi,
   I wrongly used the three-form open for code that is supposed to be
compatible before 5.6.0, so I've reverted that particular change.

Apart from this, I'm putting the whole diff for sake of discussion.

Cheers,

   Flavio.

On Sat, Aug 29, 2009 at 2:44 AM, Flavio Poletti <polettix@gmail.com> wrote:

> Hi,
>     I tried a bit of cleanup in perldata as well. Usual stuff: using
> lexical filehandles when possible, deprecate use of non-lexical filehandles,
> add 'my', use three-argument open().
>
> Changes are here:
>
> http://github.com/polettix/perl/tree/modern-perldata
> git@github.com:polettix/perl.git branch modern-perldata
>
> Commit history here:
>
> http://github.com/polettix/perl/commits/modern-perldata/
>
> Cheers,
>
>    Flavio.
>



diff --git a/pod/perldata.pod b/pod/perldata.pod
index 3c1a95e..79fdf5e 100644
--- a/pod/perldata.pod
+++ b/pod/perldata.pod
@@ -332,7 +332,7 @@ expression as a subscript.)  The following code segment
prints out "The
 price is $Z<>100."
 X<interpolation>

-    $Price = '$100'; # not interpolated
+    my $Price = '$100'; # not interpolated
     print "The price is $Price.\n"; # interpolated

 There is no double interpolation in Perl, so the C<$100> is left as is.
@@ -351,8 +351,8 @@ variable name from a following double-colon or an
apostrophe, since
 these would be otherwise treated as a package separator:
 X<interpolation>

-    $who = "Larry";
-    print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
+    my $who = "Larry";
+    print $passwd_fh "${who}::0:0:Superuser:/:/bin/perl\n";
     print "We use ${who}speak when ${who}'s here.\n";

 Without the braces, Perl would have looked for a $whospeak, a
@@ -459,7 +459,7 @@ by joining the elements with the delimiter specified in
the C<$">
 variable (C<$LIST_SEPARATOR> if "use English;" is specified),
 space by default.  The following are equivalent:

-    $temp = join($", @ARGV);
+    my $temp = join($", @ARGV);
     system "echo $temp";

     system "echo @ARGV";
@@ -490,23 +490,23 @@ In a context not requiring a list value, the value of
what appears
 to be a list literal is simply the value of the final element, as
 with the C comma operator.  For example,

-    @foo = ('cc', '-E', $bar);
+    my @foo = ('cc', '-E', $bar);

 assigns the entire list value to array @foo, but

-    $foo = ('cc', '-E', $bar);
+    my $foo = ('cc', '-E', $bar);

 assigns the value of variable $bar to the scalar variable $foo.
 Note that the value of an actual array in scalar context is the
 length of the array; the following assigns the value 3 to $foo:

-    @foo = ('cc', '-E', $bar);
-    $foo = @foo;                # $foo gets 3
+    my @foo = ('cc', '-E', $bar);
+    my $foo = @foo;                # $foo gets 3

 You may have an optional comma before the closing parenthesis of a
 list literal, so that you can say:

-    @foo = (
+    my @foo = (
         1,
         2,
         3,
@@ -515,7 +515,7 @@ list literal, so that you can say:
 To use a here-document to assign an array, one line per element,
 you might use an approach like this:

-    @sauces = <<End_Lines =~ m/(\S.*\S)/g;
+    my @sauces = <<End_Lines =~ m/(\S.*\S)/g;
         normal tomato
         spicy tomato
         green chile
@@ -554,13 +554,14 @@ A list value may also be subscripted like a normal
array.  You must
 put the list in parentheses to avoid ambiguity.  For example:

     # Stat returns list value.
-    $time = (stat($file))[8];
+    my $time = (stat($file))[8];

     # SYNTAX ERROR HERE.
-    $time = stat($file)[8];  # OOPS, FORGOT PARENTHESES
+    my $time = stat($file)[8];  # OOPS, FORGOT PARENTHESES

     # Find a hex digit.
-    $hexdigit = ('a','b','c','d','e','f')[$digit-10];
+    my $hexdigit = ('a','b','c','d','e','f')[$digit-10]; # OR
+    my $hexdigit = ('a'..'f')[$digit-10];

     # A "reverse comma operator".
     return (pop(@foo),pop(@foo))[0];
@@ -568,7 +569,7 @@ put the list in parentheses to avoid ambiguity.  For
example:
 Lists may be assigned to only when each element of the list
 is itself legal to assign to:

-    ($a, $b, $c) = (1, 2, 3);
+    my ($a, $b, $c) = (1, 2, 3);

     ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);

@@ -576,12 +577,12 @@ An exception to this is that you may assign to
C<undef> in a list.
 This is useful for throwing away some of the return values of a
 function:

-    ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
+    my ($dev, $ino, undef, undef, $uid, $gid) = stat($file);

 List assignment in scalar context returns the number of elements
 produced by the expression on the right side of the assignment:

-    $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2
+    my $x = (($foo,$bar) = (3,2,1));    # set $x to 3, not 2
     $x = (($foo,$bar) = f());           # set $x to f()'s return count

 This is handy when you want to do a list assignment in a Boolean
@@ -593,7 +594,7 @@ performing an operation in list context and then
counting the number of
 return values, by assigning to an empty list and then using that
 assignment in scalar context. For example, this code:

-    $count = () = $string =~ /\d+/g;
+    my $count = () = $string =~ /\d+/g;

 will place into $count the number of digit groups found in $string.
 This happens because the pattern match is in list context (since it
@@ -603,15 +604,15 @@ context will translate that into the number of
elements (here, the
 number of times the pattern matched) and assign that to $count. Note
 that simply using

-    $count = $string =~ /\d+/g;
+    my $count = $string =~ /\d+/g;

 would not have worked, since a pattern match in scalar context will
 only return true or false, rather than a count of matches.

 The final element of a list assignment may be an array or a hash:

-    ($a, $b, @rest) = split;
-    my($a, $b, %rest) = @_;
+    my ($a, $b, @rest) = split;
+    my ($a, $b, %rest) = @_;

 You can actually put an array or hash anywhere in the list, but the first
one
 in the list will soak up all the values, and anything after it will become
@@ -621,7 +622,7 @@ A hash can be initialized using a literal list holding
pairs of
 items to be interpreted as a key and a value:

     # same as map assignment above
-    %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);
+    my %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);

 While literal lists and named arrays are often interchangeable, that's
 not the case for hashes.  Just because you can subscript a list value like
@@ -637,7 +638,7 @@ interpreted as a string -- if it's a bareword that would
be a legal simple
 identifier (C<< => >> doesn't quote compound identifiers, that contain
 double colons). This makes it nice for initializing hashes:

-    %map = (
+    my %map = (
                  red   => 0x00f,
                  blue  => 0x0f0,
                  green => 0xf00,
@@ -645,7 +646,7 @@ double colons). This makes it nice for initializing
hashes:

 or for initializing hash references to be used as records:

-    $rec = {
+    my $rec = {
                 witch => 'Mable the Merciless',
                 cat   => 'Fluffy the Ferocious',
                 date  => '10/31/1776',
@@ -653,7 +654,7 @@ or for initializing hash references to be used as
records:

 or for using call-by-named-parameter to complicated functions:

-   $field = $query->radio_group(
+   my $field = $query->radio_group(
                name      => 'group_name',
                values    => ['eenie','meenie','minie'],
                default   => 'meenie',
@@ -671,7 +672,7 @@ An array is subscripted by specifying a dollar sign
(C<$>), then the
 name of the array (without the leading C<@>), then the subscript inside
 square brackets.  For example:

-    @myarray = (5, 50, 500, 5000);
+    my @myarray = (5, 50, 500, 5000);
     print "The Third Element is", $myarray[2], "\n";

 The array indices start with 0. A negative subscript retrieves its
@@ -681,7 +682,7 @@ value from the end.  In our example, C<$myarray[-1]>
would have been
 Hash subscripts are similar, only instead of square brackets curly brackets
 are used. For example:

-    %scientists =
+    my %scientists =
     (
         "Newton" => "Isaac",
         "Einstein" => "Albert",
@@ -697,19 +698,19 @@ X<slice> X<array, slice> X<hash, slice>
 A common way to access an array or a hash is one scalar element at a
 time.  You can also subscript a list to get a single element from it.

-    $whoami = $ENV{"USER"};             # one element from the hash
-    $parent = $ISA[0];                  # one element from the array
-    $dir    = (getpwnam("daemon"))[7];  # likewise, but with list
+    my $whoami = $ENV{"USER"};             # one element from the hash
+    my $parent = $ISA[0];                  # one element from the array
+    my $dir    = (getpwnam("daemon"))[7];  # likewise, but with list

 A slice accesses several elements of a list, an array, or a hash
 simultaneously using a list of subscripts.  It's more convenient
 than writing out the individual elements as a list of separate
 scalar values.

-    ($him, $her)   = @folks[0,-1];              # array slice
-    @them          = @folks[0 .. 3];            # array slice
-    ($who, $home)  = @ENV{"USER", "HOME"};      # hash slice
-    ($uid, $dir)   = (getpwnam("daemon"))[2,7]; # list slice
+    my ($him, $her)   = @folks[0,-1];              # array slice
+    my @them          = @folks[0 .. 3];            # array slice
+    my ($who, $home)  = @ENV{"USER", "HOME"};      # hash slice
+    my ($uid, $dir)   = (getpwnam("daemon"))[2,7]; # list slice

 Since you can assign to a list of variables, you can also assign to
 an array or hash slice.
@@ -740,19 +741,19 @@ values of the array or hash.

 A slice of an empty list is still an empty list.  Thus:

-    @a = ()[1,0];           # @a has no elements
-    @b = (@a)[0,1];         # @b has no elements
-    @c = (0,1)[2,3];        # @c has no elements
+    my @a = ()[1,0];           # @a has no elements
+    my @b = (@a)[0,1];         # @b has no elements
+    my @c = (0,1)[2,3];        # @c has no elements

 But:

-    @a = (1)[1,0];          # @a has two elements
-    @b = (1,undef)[1,0,2];  # @b has three elements
+    my @a = (1)[1,0];          # @a has two elements
+    my @b = (1,undef)[1,0,2];  # @b has three elements

 This makes it easy to write loops that terminate when a null list
 is returned:

-    while ( ($home, $user) = (getpwent)[7,0]) {
+    while (my ($home, $user) = (getpwent)[7,0]) {
         printf "%-8s %s\n", $user, $home;
     }

@@ -798,11 +799,11 @@ Another use for typeglobs is to pass filehandles into
a function or
 to create new filehandles.  If you need to use a typeglob to save away
 a filehandle, do it this way:

-    $fh = *STDOUT;
+    my $fh = *STDOUT;

 or perhaps as a real reference, like this:

-    $fh = \*STDOUT;
+    my $fh = \*STDOUT;

 See L<perlsub> for examples of using these as indirect filehandles
 in functions.
@@ -811,6 +812,8 @@ Typeglobs are also a way to create a local filehandle
using the local()
 operator.  These last until their block is exited, but may be passed back.
 For example:

+    # Avoid this approach unless you need compatibility with Perl
+    # before 5.6.0. See 'myopen' below for a more modern approach.
     sub newopen {
         my $path = shift;
         local  *FH;  # not my!
@@ -837,13 +840,14 @@ largely eliminates the need for typeglobs when opening
filehandles
 that must be passed around, as in the following example:

     sub myopen {
-        open my $fh, "@_"
-             or die "Can't open '@_': $!";
+        my $path = shift;
+        open my $fh, '<', $path
+             or die "Can't open '$path': $!";
         return $fh;
     }

     {
-        my $f = myopen("</etc/motd");
+        my $f = myopen('/etc/motd');
         print <$f>;
         # $f implicitly closed here
     }
@@ -859,6 +863,12 @@ have the advantage of not hiding different types of the
same name
 during the local().  See the bottom of L<perlfunc/open()> for an
 example.

+Note that the above example will not work for Perl before 5.8.0,
+even though Perl 5.6.0 already supports the three-argument form
+of C<open()>. In this case, you have to resort to the anonymous
+filehandle creation provided by either the Symbol module or by
+IO::Handle.
+
 =head1 SEE ALSO

 See L<perlvar> for a description of Perl's built-in variables and

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About