- 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
|
#
¿
Jul 24, 2016 11:57
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 2, 2024 13:12
|
|
- 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
|
#
¿
Jul 24, 2016 13:04
|
|
- FreshFeesh
- Jun 3, 2007
-
Drum Solo
|
Thank you for the suggestions, they're certainly helping and things look a lot better.
|
#
¿
Jul 24, 2016 13:38
|
|