in reply to split (grep)

If your list is short, using grep on an array is fine. But this means that you are reading the whole array (second list) each time, which is quite inefficient if the list is long. In that case, using a hash for the second list is a better solution. Re-using toolic's data sample, it could look like this:
use warnings; use strict; my @foo = qw/tom steve bill roger bob/; my %bar = (roger => 99, steve => 56, ted => 88, tom => 54); for my $name (@foo) { print "$name : $bar{$name} \n" if exists $bar{$name}; }
which prints:
tom : 54 steve : 56 roger : 99
I understand that you are reading your data from files, so populating a hash is not more complicated than filling an array. You just have to do the split before populating the hash, instead of doing it later.

Actually, even with a short list, I think that I would probably prefer the hash-based solution.

Replies are listed 'Best First'.
Re^2: split (grep)
by tbone654 (Beadle) on Oct 23, 2014 at 21:30 UTC

    I understand why the hash-based solution makes more sense for performance. Especially in a "fancy" solution. I guess I just want to be able to split on the grep statement as an argument if I needed to... If I can...

    This started out as a one liner "brute force" grep replacement in case I needed more than a single or just a few members of the first list...

    perl -ne 'next if(!/tom/ && !/steve/) ; printf("%10s %5s",(split/;/)[0 +,1]);' list.txt tom 54 steve 56

    Thank you for the input

      I settled on this for the moment, as it preserves the order of the first list, which is a requirement.

      @foo = qw/tom steve bill roger bob/; @bar = qw/roger;99 steve;56 ted;88 tom;54/; foreach $line(@foo){ foreach $line1(@bar){ @split1=(split/;/,$line1); if($line =~ $split1[0]){ printf("%5s %3s\n",$split1[0],$split1[1]); } } } __END__ tom 54 steve 56 roger 99
      Thank you for the suggestions