Karger78 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, What the code does below is cycles though an array and check's if there is a zip file contained. If no zips are in the array then exit. The code below is a bit lenghty, so I was wondering if there is a better way to write this. The code aready works, just looking to make it more efficent.
##If No ZIP we must exit as there is nothing to do. my $uCount; my $zipCheck=0; foreach (@uploads ) { if($uploads[$uCount] =~ /\.zip\z/) { $zipCheck++; } $uCount++; } if($zipCheck == 0) { print "There were no zip files\n"; print "Exiting"; exit(0); }

Replies are listed 'Best First'.
Re: Faster Method for check function.
by Limbic~Region (Chancellor) on Jun 16, 2009 at 13:33 UTC
    Karger78,
    Take a look at List::Util's first().
    # Added example my $have_zip = first { /\.zip\z/) } @uploads; die "No zipped files to process" if ! $have_zip;

    Cheers - L~R

Re: Faster Method for check function.
by rovf (Priest) on Jun 16, 2009 at 13:40 UTC

    Hmmm... your subject line says "Faster Method", and your posting asks for "less lengthy way", which is not necessarily the same. As for the timing the alternatives, I leave it to you as an exercise. A less lengthy version would be

    my $zipCheck=grep /\.zip\z/,@uploads; unless($zipCheck) { ... exit(0); }

    -- 
    Ronald Fischer <ynnor@mm.st>
      Your correct, I ment less lenghty way :)
        I ment less lenghty way

        ... in which case we could further shorten the unless($zipcheck) by 3 characters to if(!$zipcheck)...

        -- 
        Ronald Fischer <ynnor@mm.st>
Re: Faster Method for check function.
by ikegami (Patriarch) on Jun 16, 2009 at 13:50 UTC

    $uCount is totally useless. For/foreach aliases $_ to each element of the array.

    my $zipCheck; for (@uploads) { if (/\.zip\z/) { ++$zipCheck; last; } } die "There were no zip files\n" if !$zipCheck;
      $uCount is totally useless.

      plus, it was uninitialized, so I wonder whether the original code worked in the first place...

      -- 
      Ronald Fischer <ynnor@mm.st>
        It would have worked, but it would have issued a warning
Re: Faster Method for check function.
by Utilitarian (Vicar) on Jun 16, 2009 at 13:36 UTC
    quick and dirty oneline example
    perl -e '@files=qw(file.txt myzip.zip zip_archive.tgz newfile.zip);@z +ips=grep {m/\.zip$/;}@files;$zip_count=@zips;print "\n$zip_count zipf +iles: @zips\n";' 2 zipfiles: myzip.zip newfile.zip