vendredi 26 juin 2015

Perl - Concatenate non-empty strings

I'm in need of a little help "optimizing" my code because I'm convinced there's a better, cleaner way to do it. I have 6 variables that are created by being parsed out of a longer string:

Year
Make
Model
Color
ColorLower
Style

Depending on the record I may have details in some or all of these variables. In most cases, though, some are blank. Following the variables being populated I add them into a database field that is the description of a car/vehicle.

Currently my if/else block goes one by one and if a variable has a non-zero length, the concatenated description variable

if (length($Year)>0)
{
    $Description == $Description + " " + Year
}
elsif (length($Make) > 0)
    $Description == $Description + " " + $Make
}   ...and so on

TMTOWTDI definitely applies here, and I always marvel at the elegant one-liners that the experts come up with. Although what I have now is working, I'd be interested in hearing is there is a shorter, more compact way that I could maximize my code.

Thanks all.

Aucun commentaire:

Enregistrer un commentaire