Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
FreshFeesh
Jun 3, 2007

Drum Solo
I'm trying to iterate through an alphabetized list and edit/remove entries based on particular criteria, but as I scale up the code I want to make sure I'm being as clean as possible, since I haven't touched this stuff in a while.

code:
@array = ('cat', 'dog 1', 'dog 2', 'dog 3', 'duck');

Desired output:    cat | dog 1, 2, 3 | duck
Here's my code which does the job, but looks fairly inefficient to me:
code:
for my $i (0 .. $#array) {
	$array[$i-1] =~ m/(\w+)\b/;
	if ($array[$i] =~ m/^$1\b/) {
		$array[$i] =~ m/(\d+)$/;
		$output[-1] .= ", $1";
	}
	else { push(@output, $array[$i]); }
}
It outputs correctly, but I'd be grateful for any suggestions you guys have for ways I can clean it up, so when I scale it out to a more complicated list it's easier to manage.

FreshFeesh fucked around with this message at 12:06 on Jul 24, 2016

Adbot
ADBOT LOVES YOU

FreshFeesh
Jun 3, 2007

Drum Solo
I considered that, but unfortunately my data is more akin to
code:
Favorite Food: Spaghetti
Favorite Food: Tofu Lasagna
Green Beans 1
Green Beans 2
I like monkeys
Favorite Drink: Coors
Which makes splitting on whitespace problematic. I ended up with two different tests, one for lines ending on a number and other specific entries which would contain a colon as a delimiter:
code:
for my $i (0 .. $#newout) {
	if ($newout[$i] =~ m/\d+$/) {
		$newout[$i-1] =~ m/^([a-zA-Z\s]+)\d*/;
		if ($newout[$i] =~ m/^$1/) {
			$newout[$i] =~ m/(\d+)$/;
			$output[-1] .= ", $1";
		} else { 
			push(@output, $newout[$i]); 
		}
	}
	elsif ($newout[$i] =~ m/^Favorite Drink:/ or $newout[$i] =~ m/^Favorite Food:/ or $newout[$i] =~ m/^Something Else:/ or $newout[$i] =~ m/^Dance Party:/) {
		$newout[$i-1] =~ m/^([\w\s]+)/;
		if ($newout[$i] =~ m/^$1/) {
			$newout[$i] =~ m/: ([\w\s]+)$/;
			$output[-1] .= ", $1";
		} else { 
			push(@output, $newout[$i]); 
		}
	}
	else { 
		push(@output, $newout[$i]); 
	}
}
(I know my variable names are crap)

FreshFeesh fucked around with this message at 13:09 on Jul 24, 2016

FreshFeesh
Jun 3, 2007

Drum Solo
Thank you for the suggestions, they're certainly helping and things look a lot better.

  • Locked thread