in reply to Re: How to use sprintf %n formatting pattern
in thread How to use sprintf %n formatting pattern

the arguments to printf need to be evaluated before printf goes about the business of generating its output

I'm not sure what you mean by this - as far as I know the arguments are scalars, and it doesn't look at them until it needs to.

I suspect you probably could achieve this with a tied scalar dynamically returning $max_width - $stored_width. I think it'd be a pretty insane thing to do unless there was some really strong reason not to split it into two prints, but I'm ok with a bit of insanity, I might have a go at it after some sleep.

Replies are listed 'Best First'.
Re^3: How to use sprintf %n formatting pattern
by GrandFather (Saint) on Jun 09, 2022 at 03:38 UTC

    Consider:

    my $str = '1234567890' x 6; my $prefixLen; printf "Prefix stuff %n%s\n", $prefixLen, substr $str, 0, 35 - $prefix +Len;

    What value does substr see for $prefixLen? How can printf get the substr generated parameter generated after printf has set about generating the output?

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

      By using a sprintf parameter to determine the width:

      my $str = '1234567890' x 6; my $prefixLen; my $magicLimit = tie_me_a_scalar(sub { $max_width - $prefixLen }); printf "Prefix stuff %n%.*s", $prefixLen, $magicLimit, $str;

      Update: corrected %*s to %.*s

        It's not clear to me how a tied scalar gets around the evaluation order issue with printf's arguments. Maybe you could provide a fully worked example?

        Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond