for (@strings) { my $temp = ""; if (($temp) = $_ =~ m/^([^_]{2}_[^_]+)_?/) { print $temp; } elsif (($temp) = $_ =~ m/^([^_]+)/) { print $temp; } }