Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

perl grep

Status
Not open for further replies.

pmcmicha

Technical User
May 25, 2000
353
I am trying to do the following with no success and I cannot seem to find any good documentation on this problem.


open(LIST,"<test.txt");
@list = <LIST>;
close(LIST);

foreach $value (@unq) {\
chomp($value);
@ent = grep /^$value\|/, @list;
}


When I try this, the variable $value doesn't seem to work in the grep statement. The @ent array ends up with 0 entries even though it should have at least one inside of it. If I exchange $value for an unique entry like 831, then this works. I am unsure of this is not working.

Thanks.
 
it could be because you are redefining the @ent array each time you loop through @unq. Try this and see what you get:

Code:
open(LIST,"<test.txt");
@list = <LIST>;
close(LIST);

my @ent = ();
for my $i (0 .. $#unq) {\
    chomp($unq[$i]);
    $ent[$i] = grep /^$unq[$i]\|/, @list;
}

now @ent should hopefully contain a list of returned values from the grep function for each element of @unq. But this might work better stored in a hash (%ent) anyway:

Code:
open(LIST,"<test.txt");
@list = <LIST>;
close(LIST);

my %ent = ();
for my $i (0 .. $#unq) {\
    chomp($unq[$i]);
    $ent{$i} = grep /^$unq[$i]\|/, @list;
}

foreach my $keys (sort {$a <=> $b} keys %ent) {
   print "Index# $_ of \@unq returned: $ent{$keys}\n";
}

or something similar to that :)
 
Or
Code:
foreach $value (@unq) {\
    chomp($value);
    [b]push(@ent, grep /^$value\|/, @list);[/b]
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top