perl.beginners
[Top] [All Lists]

Re: Curly braces and the logic of PERL

Subject: Re: Curly braces and the logic of PERL
From: Mr. Shawn H. Corey
Date: Mon, 27 Oct 2008 14:36:20 -0400
Newsgroups: perl.beginners

On Mon, 2008-10-27 at 17:05 +0000, Brian wrote:
> Hello
> 
> Years ago I used to work with FORTRAN, RPG GAP 2 and a smidgeon of basic.
> Code was written one line at a time, the first section of code was Input 
> data, the next section was calculations, the last section was output.
> (For example, in the sample of code below, the "while" line would have 
> been written on one line instead of 3)
> 
> Why is it "good practice" to write PERL the way it is done?

Much of what is good practise is simply historic; it was done that way
in the past, so it's done that way now.  The rule for writing "good"
code is to design it as though a recently-graduated new-hire will be
maintaining it...because they will be.  :)


> Why is it that some code has no curly braces after print; whilst in 
> others I sometimes see one or more curly braces after it?
> Will there be a time when print; will fail because there isn't a curly 
> brace following it, even though an equal number of left & right braces 
> precede it?
> I appreciate I have the right to lay out my code in any way I see fit, I 
> would just like to see the reasoning.
> 
> An example of something confusing me is in the sample below
> find sub {
>        return unless -f;
>        open my $FH, '<', $_ or die "Cannot open '$_' $!";
>        while ( <$FH> ) {
>            /\Q$string/ && print $REPORT "$File::Find::name\n" and
>   return;
>            }}, '/test';
> 
> Why isn't the last line
>           }, '/test';}

This code is written this way because the coder has been playing too
much Perl Golf ;)  The objective of Perl Golf is to write a program to
do a simple task in the least number of characters possible.  This, of
course, makes it harder to read.

Another way to write the above:

# wanted -- a sub for File::Find::find()
#
#   $_ contains the basename of the file
#
#   $File::Find::name contains the full path to the file
#
#   $string is a global containing the string to look for;
#           it is NOT a regular expression;
#           all characters in it are matched
#
#   $REPORT is a global file handle to the output file;
#           it must be opened for writing
#
sub wanted {
    return unless -f $File::Find::name;  # ignore directories, symbolic links, 
etc.

    open my $FH, '<', $_ or die "Cannot open '$_' $!";
    while (<$FH>) {
        if (/\Q$string/) {
            print $REPORT "$File::Find::name\n";
            return;
        }
    }

    return;
}

find( \&wanted, '/test' );




-- 
Just my 0.00000002 million dollars worth,
  Shawn

Linux is obsolete.
-- Andrew Tanenbaum


<Prev in Thread] Current Thread [Next in Thread>