in reply to Trying to avoid 9 conditionals
Any time you find yourself making an ordered series of scalars, for example: $item_1, $item_2, ... you should consider using an array.
If you store your major, minor, and revision elements in an array you can operate on them as a group.
use strict; # always use warnings; # always use diagnostics; # a pretty good idea # Since I chose to use a couple of arrays to hold my # version info and update status, I'll make some # constants to make accessing them more hashlike. use constant MAJOR => 0; use constant MINOR => 1; use constant REV => 2; use constant KEYWORDS => qw( major minor revision ); use constant VERSION_ELEMENTS => ( MAJOR, MINOR, REV ); # test data my $old_version = '8.3.1'; my $new_version = '9.3.1'; # get an array with true values that indicate changes. my @updated = compare_versions( $old_version, $new_version ); # break new version string into an array my @new_version = split_version( $new_version ); # Generate a list of commands to print # If you have other processing to do as you make # your command list a foreach loop may make more sense # than using map. my @commands = map { $updated[$_] # did we update this field? ? update_aht_command( # if so, generate a command (KEYWORDS)[$_], $new_version[$_], "#DBVersion=$new_version", ) : (); # otherwise put nothing in the command lis +t. } VERSION_ELEMENTS; print @commands; # make version strings into arrays. sub split_version { my $version = shift; return split /\./, $version; } # compare version strings. # generate array of changes. sub compare_versions { my $old = shift; my $new = shift; # convert version strings to arrays my @old = split_version($old); my @new = split_version($new); # handle a length mismatch. my $last = $#old > $#new ? $#old : $#new; # make a list with true values where changes have occurred. my @updated = map { $old[$_] != $new[$_] } (0..$last); # return the list. return @updated; } sub update_aht_command { my $keyword = shift; my $new_value = shift; my $comment = shift; return join '', "Update aht set $keyword = $new_value", defined $comment ? ( "\t"x3, $comment ) : ( ) ,"\n"; }
Based on what I see in your sample code, I'd suggest you take a look at print, printf, and the qoute and quote-like operators section of perlop. Reading map should help with understanding my solution.
TGI says moo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trying to avoid 9 conditionals
by GrandFather (Saint) on Oct 15, 2008 at 22:53 UTC | |
by TGI (Parson) on Oct 16, 2008 at 00:51 UTC |