On Thu, Sep 12, 2002 at 05:04:20PM -0700, Harry Putnam wrote:
> david <[EMAIL PROTECTED]> writes:
> 
> I must be a real dunce, but I still don't get the point.
> If a bad regex is given, I want the program to stop.
> 
> Your script above doesn't spit an error, it just fails and gives some
> other error.
> 
> cat chop2.pl
> #!/usr/local/bin/perl -w
> use strict;
> 
> my $reg = shift;
> 
> while(<STDIN>){
>         chomp;
>         eval{
>                 print "$_\n" if(/$reg/o);
>         }
>         print "ERROR: $@\n" if($@);
> }
> 
> ../chop2.pl '\' Mail/xfce/*
> $ ./chop2.pl '\'  ~/Mail/xfce/*
> syntax error at ./chop2.pl line 12, near "print"
> Execution of ./chop2.pl aborted due to compilation errors.

The original code does have a syntax error; there should be a ";" after the
eval:

    #!/usr/local/bin/perl -w
    use strict;
 
    my $reg = shift;
 
    while(<STDIN>){
        chomp; 
        eval{  
           print "$_\n" if(/$reg/o);
        };
        print "ERROR: $@\n" if($@);
     }

The original poster's point remains, however.  If you want the program to
stop if the regex compilation failes, do something else if $@:

    if ($@) {
        print "ERROR: $@\n";
        exit(1);
    }


I haven't been following this thread, so perhaps there is a reason for doing
this the way it's being done, but I would change the code to do something
more along the lines of:

    #!/usr/bin/perl -w

    use strict;


    my $regex;
    eval { $regex = qr/$ARGV[0]/ };
    if ($@) { ... }
 
    while (<STDIN>) {
        chomp;
        print if /$regex/;
    }

The functional difference is where and how the regex is checked for
validity.  Instead of checking its validity each time through the loop, it's
compiled and checked once, before entering the loop.


Michael
--
Administrator                      www.shoebox.net
Programmer, System Administrator   www.gallanttech.com
--

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to