Ms. T. has asked for the wisdom of the Perl Monks concerning the following question:

I have written a perl script that requires STDN from the user. From there I go into a loop. The statements are executed correctly; however, when the result prints I get a carriage return after the number of days and the = 86400 is on the next line. I want the result to look like this:
[1] day = [86400]seconds.
The day needs to become days when it is greater than 1 and I'm not sure how to get the brackets. Any suggestions would be great! Ms. T.

Edited by davido to wrap proposed output in code tags

Replies are listed 'Best First'.
Re: Formatting in Perl
by davido (Cardinal) on Oct 01, 2004 at 03:15 UTC

    You didn't show us any code that might give us some indication as to what you're doing wrong. You should post somewhere less than ten lines of code (in this case) that mimicks the problem. (10 is an arbitrary number, but for such a simple problem is probably sufficient).

    If you want me to guess, I'll say your problem is that you are accepting the number of days as input, and forgetting to chomp that input. When the user types "1<enter>", that is captured into the recipient variable as "1\n" (in other words, enter is preserved as a \n (newline) character). chomp the input and the problem will go away, if my guess as to what you are doing wrong is correct.

    As for figuring out how to print all that:

    print "[$days] day", ($days != 1) ? 's' : '', ' = [', $days * 24 * 60 * 60, "] seconds.\n";

    ...should do the trick.


    Dave

      printf makes this sort of thing so much more readable....

      printf "[$days] day%s = [%d] seconds.\n", ($days!=1)?'s':'', $days*24* +60*60,
        How do you get your code to look like code when you post?
Re: Formatting in Perl
by graff (Chancellor) on Oct 01, 2004 at 03:23 UTC
    davido is right in all respects, though I would handle the plural a little differently (for clarity, I think):
    chomp $number_of_days; # assuming this came from <STDIN> my $plural = ( $number_of_days == 1 ) ? '' : 's'; print "\[$number_of_days\] day$plural = \[$number_of_sec\] seconds.\n +";

      You don't need to escape the [ ]. If you want to use a name for the plural suffix $s is quite readable and self documenting :-)

      print "[$days] day$s = [$secs] seconds.\n";