on Tue, 11 Jun 2002 13:17:57 GMT, [EMAIL PROTECTED]
(David Vd Geer Inhuur Tbv Iplib) wrote: 

> I am currently almost done with my current job.
> As I am reviewing my scripts the foreach-loop started to anoy me.
> 
> I am afraid this is slowing down the script. Does anyone know a
> faster way to do the following :

Here's how I would do it:

    #! perl -w
    use strict;  # not after the facts, but from the start
    
    # $pwuser set before. Purpose - find corresponding $group
    while (<DATA>) {
        my ($group, @users) = split /[:\s]+/;
        $groups{$_} = $group for (@users);
    }
    my %translation = ( htuser => 'iclab',
                        phil   => 'phil',
                        all    => 'all'   );
                                    
    my $group = $translation{$groups{$pwuser}} || "none";
    print "$pwuser - $group\n";

    __DATA__
    htuser: user1 user2 user3 manyothers
    phil: user4 user5 manymore
    all: external1 external2 etc

Some comments on your code follows:

> open(FH, "< $groupfile");

Always check the return value of a system call.

> @usrs = <FH>;
> close FH;
> 
>  $htusr = (grep {/htuser: /} @usrs)[0] ;
>  $phi = (grep {/phil: /} @usrs)[0] ;
>  $al = (grep {/all: /} @usrs)[0] ;

Look at the repeating (hardcoded) patterns which are repeated 
throughout the program, hence your 'bad feeling about the repeating 
foreach's'.

> 
>  @htuser = split(/ /, $htusr);
>  @phil = split(/ /, $phi);
>  @all = split(/ /, $al);
> 
>  foreach $htuser(@htuser) {
>   chomp $htuser;
>   if ( "$pwuser" eq "$htuser" ) { $group = "iclab"; }

Don't put quotes around single variables.

>  }
>  foreach $phil(@phil) {
>   chomp $phil;
>   if ( "$pwuser" eq "$phil" ) { $group = "phil"; }
>  }
>  foreach $all(@all) {
>   chomp $all;
>   if ( "$pwuser" eq "$all" ) { $group = "all"; }
>  }
>  if(!($group)) { $group = "none"; }

More 'Perl-like':

    $group || = 'none';

 
> I know I should have used Strict,
> [...]
> It's only a pain to correct it afterwards :(

That's why you should start with it from the beginning.

-- 
felix

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

Reply via email to