0

Can someone explain to me the result of the following script in zsh:

#!/bin/zsh
var1=var2
var2=first
var3=second
echo var1="$var1"
echo var2="$var2"
echo var3="$var3"
echo '${${(P)var1::=var3}}'="${${(P)var1::=var3}}"
echo var1="$var1"
echo var2="$var2"
echo var3="$var3"
echo ------------
var1=var2
var2=first
var3=second
echo var1="$var1"
echo var2="$var2"
echo var3="$var3"
echo '${(P)var1::=var3}'="${(P)var1::=var3}"
echo var1="$var1"
echo var2="$var2"
echo var3="$var3"

Result:

var1=var2
var2=first
var3=second
${${(P)var1::=var3}}=second
var1=var2
var2=var3
var3=second
------------
var1=var2
var2=first
var3=second
${(P)var1::=var3}=var3
var1=var2
var2=var3
var3=second

As far as I understand the zsh manual (14.3.2 Rules), the execution of the first section (above ------) should be the following:

  1. Point 7 (apply the ::= operator) (set var1 to var3)
  2. Point 25 (apply the (P) operator) (dereference var1, get var3)
  3. Output the value of var3: 'second'

These steps agree with the following line in the result:

${${(P)var1::=var3}}=second

But why in the result the following lines appear:

var1=var2
var2=var3

instead of the expected:

var1=var3
var2=first

The execution of the second section (below ----) should be (according to the manual):

  1. Point 4 (apply the (P) operator) (dereference var1, get var2)
  2. Point 7 (apply the ::= operator) (set var2 to var3)
  3. Output the value of var2: 'var3'

The results of this section match the explanation above perfectly, so the problem is only with the first section.

0

The (P) applies before the assignment so it's:

  1. ${(P)var1::=var3} -> ${var2::=var3}
  2. -> ${var3}
  3. -> second

with var3 having been assigned to var2.

To force the other order, use ${${(P)${var1::=var3}}}

Note the note in the manual about those rules:

Note that the Zsh Development Group accepts no responsibility for any brain damage which may occur during the reading of the following rules.

1
  • You step 2. does not seem to be right. I have added the second section above to show you the distinction. The result of ${var2::=var3} is not ${var3} but ${var2}, as far as I understand how it works. – Mateusz Grotek Jun 4 '18 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.