in reply to Re: Printing based on values?
in thread Printing based on values?

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?

Replies are listed 'Best First'.
Re^3: Printing based on values?
by toolic (Bishop) on Mar 26, 2011 at 23:58 UTC
    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.

      Ahh, wonderful, thank you! That works just as you said. I do have two questions about your code though...

      What does the "qw" do in the statement

      for (qw(years months weeks days))

      When I read that entire statement to myself...I read it as "For (qw?(Every key in the hash)...print "The value of the key followed by the key" if "That key value is true."

      Does that sound right to you? I'm not trying to be a pain, I just want to understand everything in that code.

        You're welcome.

        Yes, that's a good way to read it. I listed the keys inside qw in the order you wanted. See also Quote Like Operators.