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

I am new to using loops as well as perl in general, however after reading about sprintf, and coming to the conclusion you can store a formatted variable in the sprintf function, is there a way to store, and call the formatted variable in the sprintf function in a array for use in a loop....? Thank you Jason

Replies are listed 'Best First'.
Re: Loops and variables?
by dragonchild (Archbishop) on Jan 27, 2006 at 18:42 UTC
    It sounds like you're very new to the concept of programming as well.

    The sprintf() function doesn't store anything. It takes in a set of input parameters and returns an output. It's a transformer, not a storehouse. You have to tell it where to store the result.

    This means that you could do the following:

    my @array_of_unformatted_numbers = ( 2, 5.3, 56.789, ); my @array_of_formatted_numbers = map { sprintf( "%0.2d", $_ ) } @array_of_unformatted_numbers; foreach my $formatted_number ( @array_of_formatted_numbers ) { print "The formatted number is $formatted_number.\n"; }

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: Loops and variables?
by ikegami (Patriarch) on Jan 27, 2006 at 18:47 UTC

    Your question is very confusing. Variables can't be stored in a function, for starters. (Well, there are closures, but let's avoid advanced topics of no immediate relevance.) Maybe one of the following snippets will answer your question:

    # Modifies @array in-place. foreach (@array) { $_ = sprintf($format, $_); }
    # Copies to a second array while formatting. my @formatted = map { sprintf($format, $_) } @array;
    # Same as last, but without using "map". my @formatted; for (0..$#array) { $formatted[$_] = sprintf($format, $array[$_]); }

    Does that help?

    To print the pre-formatted data, simply use the following:

    foreach (@formatted) { print($_, "\n"); }
Re: Loops and variables?
by davido (Cardinal) on Jan 28, 2006 at 06:00 UTC

    Reading this question in the context of having read Why SprintF? it occurs to me that you're talking about using sprintf to create a string that you then store in a scalar variable. ...as in my $variable = sprintf ..... (where '......' represents the rest of the parameter list). Ok, that's been covered in the previous question. So now on to the current question; can sprintf be used to store formatted data into in array so that as you loop you're able to iterate over this array of sprintf-formatted data? Yes. Here are a couple ways:

    # Here's one using 'push': my @array; push @array, sprintf "%2d", $info; push @array, sprintf "%3f", $moreinfo; # Here's another way: my @array; $array[0] = sprintf "%2d", $info; $array[1] = sprintf "%2s", $moreinfo; # And now you can iterate over the array: foreach my $item ( @array ) { print $item, "\n"; }

    Dave