Frage

It seems like the AT FIRST statement of control level processing is ideal for any commands that have to be run or variables that have to be initialised before the loop itself starts running. Given how AT commands clear columns in the work area it's one of the few uses I still see for them.

To illustrate, rather than doing this:

CLEAR lv_loopcounter.
LOOP AT lt_itab INTO ls_wa.
    ADD 1 TO lv_loopcounter.
    ...
ENDLOOP.

We could do this:

LOOP AT lt_itab INTO ls_wa.
    AT FIRST.
        CLEAR lv_loopcounter.
    ENDAT.
    ADD 1 TO lv_loopcounter.
    ...
ENDLOOP.

Here it's immediately obvious that the variable needs to be initialised for the loop to function as intended. It also makes for cleaner looking code when you have a lot of statements that need to be run prior to a loop. The only downside I see is that it moves code inside a LOOP statement when it logically shouldn't be.

Is there a best practice here? Are there hidden caveats I should be aware of?

War es hilfreich?

Lösung 2

Both variants are possible, but they are semantically different: In the first version, the command CLEAR is executed unconditionally, in the first version, it is only executed if lt_itab contains at least one line. For the actual loop implementation, the difference is irrelevant, but for an empty table, the value of the variables in question differs after the ENDLOOP statement is reached. This is not a problem as long as you handle empty tables sensibly... :-)

The only other micro-caveat of the second version is that AT FIRST will clear all non-character fields of ls_wa and set all character fields of ls_wa to '*'.

Andere Tipps

While vwegert's answer is correct for the simple loop case I've described in my question, there is a very important secondary case where AT FIRST will not function as you might expect, and that is when looping with a condition.

As SAP's AT documentation states:

The control level is defined by the first row of the internal table. The control break takes place when this row is read.

In other words, AT FIRST will not fire on the first iteration of the loop but when the absolute first row of the internal table is read. What this means is that if we loop over only a few rows of an internal table, the odds are that we won't loop over the first row. If that is the case the control block will not be entered.

As an example:

LOOP AT lt_itab INTO DATA(ls_itab) WHERE itab_col1 = iv_value.
    AT FIRST.
        CLEAR lv_loopcounter.
    ENDAT.
    ADD 1 to lv_loopcounter.
    ...
ENDLOOP.

If itab_col1 of the first internal table row matches iv_value, the loop counter will be cleared. If the first row's does not match this value, the loop counter will not be cleared!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top