|
Posted by April on June 3, 2008, 8:48 pm
Please log in for more thread options >
> > sprintf( "%s%$Fmt%s", ("%$Fmt=3D|", $TestStr, "|"))
>
> A few more lines of code showing what $Fmt and $TestStr are set to would
> be useful... I'm going to guess you were using something like
>
> =A0 =A0 my $Fmt =A0 =A0 =3D 'f';
> =A0 =A0 my $TestStr =3D '1.004';
>
> in which case you would get the string '%f=3D|1.004000|' back from
> sprintf.
>
> > This is in Perl for Dummies, 4th ed, p160.
>
> Hmmm, I would suggest you find a new book. Quite apart from the fact
> I've never heard anything good about any of the 'for Dummies' books,
> the expression you gave is *not* a clear way to write what they wanted.
> 'Learning Perl', published by O'Reilly, is the standard recommendation;
> for others, see perldoc -q book orhttp://books.perl.org.
>
> > I'm trying to understand this ...
>
> > the first part, "%s%$Fmt%s", my understanding is the format part,
> > which specifies the formats for the second part, thelist part, ("%
> > $Fmt=3D|", $TestStr, "|"):
>
> Firstly, there is no 'first part' and 'second part', and the inner set
> of parens are completely unnecessary. The important point is that
> sprintf treats its first argument specially, and uses it to format the
> rest.
>
> > %s for "%$Fmt=3D|", %$Fmt for $TestStr, and %s for "|", respectively. Is=
> > this correct?
>
> Yes.
>
> > Then what is %$Fmt, it seems a % for format and then a variable $Fmt,
> > the book did not mention any format string like this ...
>
> What you are not understanding is that there are two levels of
> intepretation going on here. (This is one of the reasons I would not
> write it like that: it's confusing.)
>
> First Perl expands the double-quoted strings, so given the values I was
> assuming above sprintf gets passed the list
>
> =A0 =A0 '%s%f%s', '%f=3D|', '1.004', '|'
>
> which I've written with single-quotes to show they aren't going to be
> expanded again by Perl. Then sprintf takes the first argument, and
> formats the rest in the appropriate places, so
>
> =A0 =A0 %s -> %f=3D|
> =A0 =A0 %f -> 1.004000
> =A0 =A0 %s -> |
>
> =A0 =A0 %s%f%s -> %f=3D|1.004000|
>
> I presume the aim here is to let you put in various values for $TestStr,
> and various formats, and show you how sprintf would intepret them.
>
> I would have writted it as
>
> =A0 =A0 sprintf "%%$Fmt=3D|%$Fmt|", $TestStr
>
> or perhaps even
>
> =A0 =A0 "%$Fmt=3D|" . sprintf("%$Fmt", $TestStr) . '|'
>
> which, although it still looks a little like line-noise, is probably
> easier to understand.
>
> Ben
>
> --
> Raise your hand if you're invulnerable.
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =
=A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0[b...@morrow.me.uk]
Thank you very much Ben for spending so much time with details and
examples, you explained really well and I think I do understand this
piece of the language now. Thanks again Ben!
|