On Jul 31, 2014, at 12:02 PM, ESChamp wrote:

> John W. Krahn wrote on 7/31/2014 3:11 AM:
>> Peter Holsberg wrote:
>>> I think I've isolated the section that is not doing what I want.
>>> 
>>> open (FHIN, "$recapfile") or die $!;
>> 
>> That would be better as:
>> 
>> open my $FHIN, '<', $recapfile or die "Cannot open '$recapfile' because: 
>> $!";
> 
> Thanks, John. As this is a beginners list and I'm an elderly beginner
> who is an occasional perl user, what makes that better?

It is better because 1) it uses the three-argument form of open instead of the 
two-argument version (the two-argument version has known risks), 2) it doesn't 
put the variable containing the file name in superfluous double-quotes, 3) it 
adds the file name to the error message, and 4) it uses a local lexical 
variable instead of a global bareword package variable.


>>> my $indexb; ## for the recapfile array
>>> my $ofile;
>> 
>> You never use this variable, it should be:
>> 
>> my @ofile;
> 
> Could you kindly explain that?

You are declaring a scalar variable $ofile, but in your code below you use the 
array variable @ofile. These are not the same thing. If you put 'use strict;' 
at the beginning of your program, Perl will inform you that you have not 
declared @ofile.


>>> # Create new array containing all the lines of recapfile up to
>>> # the string RESULTS OF BOARD 1
>>> 
>>> XYZZY:
>>>     while (<FHIN>)
>>>     {
>>>             last XYZZY if  / RESULTS OF BOARD 1/;
>>>             chomp;
>>>             $ofile[$indexb++] .= $_;
>> 
>> That would be better as:
>> 
>>     push @ofile, $_;
>>>     }
>>> close FHIN;
> 
> Exactly what lines would yours replace? Why would that be better?

  push @file, $_;

replaces 

  $ofile[$indexb++] .= $_; 

This is better because 1) it is simpler and therefore less likely to contain an 
error, 2) uses a Perl built-in function instead of hand-crafted code, 3) 
doesn't use an additional variable ($indexb), 4) doesn't use the unnecessary 
concatenation operator '.=' where a simple assignment '=' would do.

  x .= y

is equivalent to

  x = x . y

While this works in your case because the elements of @ofile are all undefined, 
and concatenating a string to an undefined value results in a simple 
assignment, it is a superfluous operation.



--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to