SAP ABAP, Variable Variables
I was modifying an ABAP program for a migration project and came across a section of code that was initially puzzling to me. I couldn't figure out why the previous developer was filling variables with field names and then assigning those variables to field symbols, until I noticed the parentheses surrounding the variable name in the assign statement. The previous developer create a variable to hold the name of a field (another variable), he then used the ASSIGN keyword to assign the parenthesized variable it to a field symbol. Field symbols are a type of memory pointer, so the field symbol pointed to the memory location specified by the value of the variable.
This sounds quite a bit more confusing than it really is, so I wrote a small sample program to demonstrate the technique. This is not something that should normally be required, but in the case I was dealing with we were parsing a table row by row and field by field in order to transform the data for migration into a different SAP system.
*&-------------------------------------------------*
*& Report ZTEST_STOLL
*&-------------------------------------------------*
REPORT ZTEST_STOLL.
DATA: lv_variable(30) TYPE c,
lv_variable_name(30) TYPE c.
FIELD-SYMBOLS: <fs_test1>,
<fs_test2>.
" This is the actual variable we are working with
"MOVE 'this is a test string' TO lv_variable.
lv_variable = 'this is a test string'.
" This is the name of the variable we are working with
"MOVE 'lv_variable' TO lv_variable_name.
lv_variable_name = 'lv_variable'.
" Assign the variable name to the field symbol
" (really point the field symbol to the variable)
ASSIGN lv_variable_name TO <fs_test1>.
" Assign the contents of the mentioned
" variable name to the field symbol
" (really point the field symbol to the variable
" name that is defined in the variable)
" The parentheses are used to dereference,
" allowing variable "variable names"
ASSIGN (lv_variable_name) TO <fs_test2>.
WRITE lv_variable.
WRITE /.
WRITE lv_variable_name.
WRITE /.
WRITE <fs_test1>.
WRITE /.
WRITE <fs_test2>.
And here is the output:
Program ZTEST_STOLLCRI
--------------------------------------------------
this is a test string
lv_variable
lv_variable
this is a test string