Traps and pitfalls in YCP

This documents is a collection of common traps and pitfalls encountered when programming with the YaST2 control language YCP.

Remember, this is an interpreted language and some issues will only surface at runtime.

The alias trap

This might be the deepest pitfall of YCP which you will fall into if you're trying to be too clever when changing lists and maps.

Have a look at this code:

{
  map `m = $[1:11, 2:12, 3:13];	// define a map
  map `m1 = m;			// save the current status in a helper map
  `m[1] = 12;			// change the original map
  return (m == m1);		// this should return false ...
}

What would you expect ? Does the above code return true or false ?

Well, it returns true because it triggers the alias trap.

Assignments in YCP don't copy complex values (like lists and maps) but rather pass references (!). So in the above example, m1 doesn't hold a copy of m but a reference.
Changing m also changes m1.

How to prevent the alias trap ?


You can prevent the alias trap by referencing an intermediate value instead of the original value. This is easily done by wrapping it in eval():

{
  map `m = $[1:11, 2:12, 3:13];	// define a map
  map `m1 = eval(m);		// reference the result of eval()
  `m[1] = 12;			// change the original map
  return (m == m1);		// this does return false.
}


Klaus Kämpf
Last modified: Wed Nov 27 11:42:21 MEST 2001