Skip to main content.
home | support | download

Back to List Archive

Re: Getting older .cgi scripts to work with

From: Bill Moseley <moseley(at)not-real.hank.org>
Date: Thu Jun 06 2002 - 17:02:23 GMT
At 09:28 AM 06/06/02 -0700, Andrew Lord wrote:
>It still needed the path to swish in the line & in the end I've found 
>that the following line gets the script kicking along nicely:
>
>my @stuff = makewordlist( shift || $pattern,  $swish );

Then you just want

   my @stuff = makewordlist( $pattern,  $swish );

shift is used to shift an array.

  my @array = ('apples', 'oranges', 'grapes');
  my $fruit = shift @array;

Now, $fruit contains "apples" and the array just contains oranges and grapes.
If you just say:

  my $fruit = shift;

then it depends on where it's used.  Typically shift is used to implicitly
shift the @_ array, which is the array passed to a function.  So you often
see:

sub dollar_to_euro {
    my $dollars = shift;
    ...
    return $euros;
}

But outside a function shift will shift the @ARGV array (the array the
contains the parameters passed to the program.  So my example program said:

  my $letter = shift || 'a';

so it says $letter is assigned either the argument passed to the program on
the command line, or the letter "a" if no arguments were passed.  Wait,
strike that.  It will use "a" if shift @ARGV is false, which can be
undefined, the empty string or the number zero.

You don't really want to use shift like that in a CGI script as you want to
get your parameters from the CGI parameters not from some parameter the web
server might pass to your program.

One last thing: 

   my @stuff = makewordlist( $pattern,  $swish );

So, it would be very good to have makewordlist() validate both parameters,
or at least the $pattern, as that might come from an external source -- the
end user.  But what if it fails validation?  How to you propagate the error
message back from makewordlist()?

There's lots of ways to do this, but one option would be to return a
reference to a hash.  

   my $word_list = makewordlist( $pattern,  $swish );

   if ( my $error_message = $word_list->{error} ) {
        show_error_page( $error_message );
        exit;
   }
 
   # not necessary to copy, but to be clear
   @word_list = @{  $word_list->{words} };

   # also not necessary, as the error_message should catch this
   # but as an example
   if ( !@word_list ) {
       shows_error_page( "Sorry no words found for letter $pattern" );
       exit;
   }

 
And then in the makewordlist function you can return things like:

   if ( $letter != /^[a-z]$/ ) {
      my %hash = (
           error => "You must enter a letter a to z";
      );
      return \%hash;
   }
   ...

   return { words => \@list_of_words };

}

Should get you going.

-- 
Bill Moseley
mailto:moseley@hank.org
Received on Thu Jun 6 17:05:52 2002