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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding a file to an array, but this code is not good

Status
Not open for further replies.

Aegir

Technical User
May 10, 2002
1
BE
hello,

I'm excluding files form being added to an array but i'm not pleased with the way I made it work.

Could you help me find a better (shorter?) piece of code?

foreach $temp_file (@ls) {
#next is bad
$add = "y";
foreach $notthisfile (@excludefiles) {
if ($temp_file eq $notthisfile) { $add = "n"; }
}
if ($add = "y") {
...
}

#previous is bad
}
 
I assume you are using perl.

why not just do this

foreach $temp_file (@ls)
{
foreach $notthisfile (@excludefiles)
{
unless ($temp_file eq $notthisfile)
{
#code here
}
}
}
 
My favorite way of doing this sort of thing is to use regular expression searching. Here's how:

Convert the array of strings you want to match against into a string, with a unique character between each element and at the beginning and the end. For example:
Code:
$excludefiles = '!' . join('!',@excludefiles) . '!';
Use a search to see if the string you want to find, bounded by the same unique character, is in the string of targets.
Code:
foreach $temp_file (@ls) {
   if ( $excludefiles =~ /!$temp_file!/ ) {
      # file is in the list
   } else {
      # file is not in the list
   }
}
I don't know if using a regular expression search is faster than the for loop or not, but I know this technique works too. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
By the way, here's a short test program I wrote that fully demonstrates the technique:
Code:
#!/usr/local/bin/perl

@exclude = ("cat","dog","rat","fish","bird");
$exclude = '!' . join('!', @exclude) . '!';

$testStr = "cat Tracy rat S. dog fish Dryden bird";
@testArray = split(/ /, $testStr);

@excluded = ();
@result = ();

foreach $testWord (@testArray) {
   if ( $exclude =~ /!$testWord!/ ) {
      push(@excluded, $testWord);
   } else {
      push(@result, $testWord);
   }
}

$result = join(' ', @result);
$excluded = join(' ', @excluded);

print "excluded: $excluded\n";
print "result: $result\n";

exit 0;
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top