in reply to Weird ? behavior of printf / sprintf
In the first step, an element of @a is being interpolated into the string. That element's index is given as %d (in your first example), which is a valid expression that produces 0, since it's an empty hash in scalar context. In the second example, the expression given as the index is invalid and produces a syntax error. In the third, the \ makes the $ literal, so no interpolation is attempted.
Some people find it easier to think of strings as being compiled rather than interpolated at runtime. So you can think of your first two examples as compiling to concatenated literals and variables:
Does your problem seem more obvious there?perl -wle 'my @a=1..9; printf $a[%d] . "\n", 4' perl -wle 'my @a=1..9; printf $a[%2d] . "\n", 4'
|
|---|