Douglas0028 has asked for the wisdom of the Perl Monks concerning the following question:

Hello again everyone. I'm having some trouble trying to figured out a method for printing a certain statement based on whether or not I have values

What I mean is, that I have four values "Years", "Months", "Weeks", and "Days". When I'm checking someone's age, one or more of those values may be 0, for instance if today was my birthday it would just be years, or if my birthday was three days ago, I would only have values for "Years" and "days." So I've been trying to figure out if there is some way to check for that, without having to write out "if" statements for every possible combination, cause that would look ugly, and there must be a better way. Ugh, please help!

Replies are listed 'Best First'.
Re: Printing based on values?
by toolic (Bishop) on Mar 26, 2011 at 23:27 UTC
    If you store your data in a hash, you could loop throught the keys and only print if each value is not 0:
    use warnings; use strict; my %age = ( years => 5, months => 0, weeks => 2, days => 0, ); for (sort keys %age) { print "$_ = $age{$_}\n" if $age{$_}; } __END__ weeks = 2 years = 5

      I think I sort of get what you mean, but I'm really new to Perl, and I'm not sure if I explained exactly what I wanted to do right, or if I'm just not understanding your code.

      In my head I think of a print statement that looks like...

      print "You are $years years $months months $weeks weeks $days days old.";

      So now if you were 28 years and 3 days old...it would only print "You are 28 years 3 days old."? Or if you were 28 years and 1 week old...it would only print "You are 28 years 1 week old." Does storing them in a hash allow me to do that?

        You could still use a hash:
        use warnings; use strict; my %age = ( years => 28, months => 0, weeks => 0, days => 3, ); print 'You are '; for (qw(years months weeks days)) { print "$age{$_} $_ " if $age{$_}; } print "old.\n"; __END__ You are 28 years 3 days old.

        But, an array may be simpler.

Re: Printing based on values?
by Douglas0028 (Novice) on Mar 27, 2011 at 00:43 UTC

    Thanks again! I really just couldn't grasp how to do that until you answered.