You are on page 1of 73

ITB258 - ABAP Programming

Lecture Week 5 Formatting Output With WRITE Program Modularisation

Objectives
This lecture aims to introduce the reader to
the ABAP WRITE Statement methods for formatting output
positioning output on the screen formatting options lines and blank lines on the screen

techniques for program modularisation


creating Forms & Functions passing parameters to forms and functions

Basic Form of WRITE


WRITE f .
outputs content of field f to the current list in its default output format basic ABAP statement for outputting data additions to the basic WRITE statement give control over
screen position, field length, decimals, exponent, format mask, colour

Default Outputs example


report zadamswk501 type type type type type type type type c n i p f t d x value value value value value value value value . 'ABCDE', '12345', 12345, 12345, 12345, '085922', '20010326', 'ABCD'. data: char(10) numc(10) integer packed float time date hex write: / / / / / /

' ----+----1----+----2----+', ' 1234567890123456789012345', 'char: ', char, /, / 'numc: ', numc, /, 'int: ', integer, /, / 'pack: ', packed, /, 'float:', float, /, / 'time: ', time, /, 'date: ', date, /, / 'hex: ', hex.

Default Outputs example

Type c n t d x i p f

Justify left left left left left right right right

Length flen flen 6 8 2*flen 11 2*flen (+1) 22

Format pad right with spaces pad left with zeros HHMMSS user defaults (DDMMYYYY) pad right with zeros pad left with zeros (suppressed) pad left with zeros (suppressed) pad left with zeros (suppressed)

Positioning Output
WRITE [AT] [/] [pos] [(len)] f .
/ denotes new line pos
horizontal position always output at that position regardless of whether there is enough space or other fields overwritten

(len)
output length if len is too short
numeric fields truncated (left), asterisk displayed all others truncated (right) with no indication

Some Examples of pos (len)


data: word(16) value '0123456789ABCDEF', col type i value 8, len type i value 5. 0120123489AB 0123456789AB *45 01234567 01

write /5(12) word. write at col(len) word. write /(3) 12345. write: /5(8) word, 25(2) word.

Formatting Options - all data types


WRITE f option1 option2 ....
LEFT-JUSTIFIED RIGHT-JUSTIFIED CENTERED UNDER g NO-GAP USING EDIT MASK m USING NO EDIT MASK NO-ZERO blanks COLOR c Output is left justified Output is right justified Output is centered Output starts under field g Blank after field f is omitted Specifies a format template m Deactivates a template All zero field replaced by Color of output specified by c

Formatting Options examples


DATA: word(10) value 'text', num(10) type n value 12345. WRITE: / / / / / / / / / 'Left Justified :', word LEFT-JUSTIFIED, 'Right Justified :', word RIGHT-JUSTIFIED, 'Centered :', word CENTERED, 'one', 'two', 'three', 'four', word UNDER 'three', word USING EDIT MASK '_:_%_8_!', 'one', 'two' NO-GAP, 'three', 'four', num, num NO-ZERO.

Formatting Options - numeric fields only


Leading sign is not output Output has d digits after decimal Type f fields exponent defined in e Type p fields are divided by 10**(r) and then rounded CURRENCY c According to definition of c in table TCURX UNIT u Number of decimal places is fixed according to the definition of u in table T006 for type p fields NO-SIGN DECIMALS d EXPONENT e ROUND r

Formatting Options examples


data: packed type p value '-12345.678', float type f value '-12345.678'. write: / / / / / / / / / / / / 'Packed', 40 'Float', packed, 40 float, 70 'default', packed NO-SIGN, 40 float NO-SIGN, 70 'no-sign', packed DECIMALS 4, 40 float DECIMALS 4, 70 'decimals 4', packed DECIMALS 2, 40 float DECIMALS 2, 70 'decimals 2', packed DECIMALS 0, 40 float DECIMALS 0, 70 'decimals 0', packed ROUND 2, 40 float ROUND 2, 70 'round 2', packed ROUND 0, 40 float ROUND 0, 70 'round 0', packed EXPONENT 2, 40 float EXPONENT 2, 70 'exponent 2', packed EXPONENT 0, 40 float EXPONENT 0, 70 'exponent 0', packed CURRENCY 'USD', 40 float CURRENCY 'USD', 70 'currency', packed UNIT 'KM', 40 float UNIT 'KM', 70 'unit' .

Formatting Options - date fields


WRITE f [date format string]
data: today type d value '20040402'. write: / today, /(10) today, / today DD/MM/YY, / today MM/DD/YY, / today DD/MM/YYYY, / today MM/DD/YYYY, / today MMDDYY, / today DDMMYY, / today YYMMDD, /(10) today using edit mask '__/__/____'.

System User Profile Own Data Defaults

Formatting Options: Colours


WRITE f COLOR [color constant | literal | = var]
COLOR sets the background colour of a list line. The colour can be specified as a pre-defined constant:
WRITE var COLOR COL_TOTAL.

or a digit from 0 to 7:
WRITE var COLOR 3.

or the value of a data element (using '='):


data row_colour = 3. WRITE var COLOR = row_colour.

Available Colours
Digit 0 1 2 3 4 5 6 7 Colour Constant COL_BACKGROUND COL_HEADING COL_NORMAL COL_TOTAL COL_KEY COL_POSITIVE COL_NEGATIVE COL_GROUP Recommended Actual for Colour Background (default) Headings List Bodies Totals Key Columns Positive Thresholds Negative Thresholds Grouping Light Grey Blue Blue Grey Yellow Cyan Green Red Orange

Formatting Options: Colours


There are 2 options that affect the way a colour is displayed:
INTENSIFIED [ON | OFF]
ON (default) bright colours OFF less intense colours (faded)

INVERSE [ON | OFF]


ON colour used for foreground text on default background OFF (default) colour used for background

Colour Format Example


data: number type i value 0. while number < 8. write: /(4) number, 7 sy-vline, ' Intensified ON ' COLOR = number, sy-vline, ' COLOR = number INVERSE. ' Intensified OFF ' COLOR = number INTENSIFIED OFF, sy-vline, ' Inverse number = number + 1. endwhile.

FORMAT
FORMAT option1 [ON|OFF] option2 [ON| OFF] ...
formatting ON applies to all subsequent output until turned off using the OFF option FORMAT option1 = var1 option2 = var2 ... var interpreted as a number should be of type i var = 0 has same effect as OFF option var > 0 has same effect as ON option with COLOR option acts like corresponding colour number

FORMAT
formatting options used in a WRITE statement overwrite the corresponding settings of a previously issued FORMAT statement for the current output for each new event the system resets all formatting options to their default values
all options have a default value of OFF except the INTENSIFIED option

FORMAT RESET
sets all formatting options to OFF in one go

tables sflight. data sum type i. top-of-page. FORMAT COLOR COL_HEADING. write: 'DATE', 20 'SEATS OCCUPIED', 50 'SEATS AVAILABLE'. start-of-selection. select * from sflight where carrid = 'AA'. if sflight-seatsocc = sflight-seatsmax. "if fully booked FORMAT COLOR COL_NEGATIVE. else. FORMAT COLOR COL_NORMAL. endif. write: / sflight-fldate UNDER 'DATE', sflight-seatsocc UNDER 'SEATS OCCUPIED', sflight-seatsmax UNDER 'SEATS AVAILABLE'. sum = sum + sflight-seatsocc. endselect. end-of-selection. uline. write: 'Total Bookings:' INTENSIFIED OFF, sum UNDER sflight-seatsocc COLOR COL_TOTAL.

Writing Symbols and Icons


There are about 200 pre-defined symbols and icons available for writing to the output list. To write a symbol (small line drawing):

WRITE symbol AS SYMBOL


To write an icon:

WRITE icon AS ICON


Must use statement:
include <symbol> | <icon> | <list>

Full list in help for WRITE (F1)

Symbols and Icons example


INCLUDE <LIST>. WRITE / 'SYMBOLS' COLOR COL_HEADING. WRITE: / SYM_PHONE AS SYMBOL, / SYM_NOTE AS SYMBOL, / SYM_FAX AS SYMBOL. SKIP. WRITE / 'ICONS' COLOR COL_HEADING. WRITE: / ICON_CALCULATION AS ICON, / ICON_PRINT AS ICON, / ICON_RED_LIGHT AS ICON, / ICON_GREEN_LIGHT AS ICON, / ICON_TIME_ZONE AS ICON, / ICON_WS_PLANE AS ICON.

Horizontal Lines ULINE [AT [/] [<pos>] [(len)] ].

OnScreen Lines & Blank Lines


WRITE [AT [/] [<pos>] [(len)] ] SYULINE.

Vertical Lines

WRITE [AT [/] [<pos>] ] SY-VLINE. WRITE [AT [/] [<pos>] ] |.


Blank Lines

SKIP [n] SKIP TO LINE n.

Creating Blank Lines


SET BLANK LINES [ON | OFF]
OFF
system suppresses blank lines created by WRITE

SKIP [n]
if n greater than lines remaining on page
produces page footer, throws to new page

at the beginning of a new page


ignored except if page created by NEWPAGE or if page is the first of a list level

If last output statement of last list page

data blank_line(50). write: / blank_line. write sy-uline. set blank lines on. write: / blank_line. write sy-uline. skip 2. write sy-uline. skip to line 10. write 'line 10'. skip to line 20. write 'line 20'. skip to line 15. write 'line 15'.

Page and Line Breaks


NEW-PAGE.
...NO-TITLE header ...WITH-TITLE ...NO-HEADING ...WITH-HEADING ...LINE-COUNT lin ...LINE-SIZE col line new page without standard list new new new new page with standard list header page without column headers page with column headers page with lin lines per page new page with col columns per

NEW-LINE.

System Fields for Lists


SY-PAGNO SY-LINNI SY-COLNO SY-TITLE Current page number Current line number Column number of current cursor position Title that appears in the title bar of the display window. Can be manipulated by:
maintaining text elements using SET TITLEBAR <titlestring>.

SY-SROWS SY-SCOLS

Current number of lines in display window Current number of columns in display window

Program Modularisation

Why Modularise?
improve program structure make the program easier to maintain and update improve readability reduce redundancy allow for component reuse event processing
ABAP is an event driven language. The processing associated with each event is written in a program module

Modularisation in ABAP
types of modules in an ABAP program
subroutines or forms
internal subroutines source code is in the same ABAP program as the calling procedure external subroutines source code of external subroutines is in an ABAP program other than the calling procedure

functions
stored in central library offer a defined interface

event handling code blocks

Subroutine Syntax
FORM subr [TABLES formal table list] [USING formal input list] [CHANGING formal output list] ENDFORM. PERFORM subr [TABLES actual table list] [USING actual input list] [CHANGING actual output list]

NOTE: No comma in parameters list

formal parameters - defined within FORM actual parameters - specified with PERFORM parameter types
input - used to pass data to subroutines output - used to pass data from subroutines input/output - pass data to & from subroutines

Passing Data By Parameters

call by reference call by value normal scoping rules apply to calling & called data items

Global & Local Data


REPORT ZSAPTEST. * Global Data TABLES: ... DATA: X, Y. * Subroutine Call PERFORM name USING X Y. * Subroutine FORM name USING A B. * Local Data DATA: S TYPE i. * Statements ENDFORM. TABLES Global Data

TABLES Global Data Formal Parameters Local Data

passing by reference
USING or CHANGING

Passing Data By Parameters

USING for input parameters that are not changed CHANGING for output parameters that are changed

passing by value
FORM subr USING VALUE(f )

report zpass_by_ref. parameters: number type i default 10. data: factorial type i value 0. PERFORM fact USING number CHANGING factorial. write: / 'factorial of ', (5) number, 'is ', (8) factorial. FORM fact USING p_number CHANGING p_factorial. p_factorial = 1. while p_number ge 1. p_factorial = p_factorial * p_number. p_number = p_number - 1. endwhile. endform. " fact

report zpass_by_ref. parameters: number type i default 10. data: factorial type i value 0. PERFORM fact USING number CHANGING factorial. write: / 'factorial of ', (5) number, 'is ', (8) factorial. FORM fact USING value(p_number) CHANGING p_factorial. p_factorial = 1. while p_number ge 1. p_factorial = p_factorial * p_number. p_number = p_number - 1. endwhile. endform. " fact

Terminating Subroutines
Unconditional termination
EXIT in the subroutine
control leaves the subroutine and processing continues immediately after the calling PERFORM statement

Conditional termination
CHECK cond in the subroutine
if cond is not satisfied, same as above

Function Modules
classified in function groups
group of functions that serve similar purposes
eg, calendar functions

stored in the function library main difference between subroutines and functions is a clearly defined interface for passing data between program and function

Functions vs. Forms


Function modules have a special screen used for defining parameters parameters are not defined via ABAP/4 statements. Different syntax is used to call a function module than to call a subroutine. Leaving a function module is accomplished via the raise statement instead of check or exit.

Function Builder
FM Group: FIBU FM_01 ... FM_02 ... FM Group: ZIBU FM_03 FM_04 ...

Maintaining Function Modules


FM_02 Interface Import Export Tables Exceptions Program Documentation Administration

Using Function Modules


REPORT ... TABLES: CALL FUNCTION FM_02 EXPORTING IMPORTING...

Building a Function

44

45

46

Testing Function Modules


from the Function Builder: Initial Screen choose Single test assign values to the import parameters press execute to display the Test Function Module: Results Screen system provides results as well as a runtime analysis of execution time

48

49

Calling Functions
CALL FUNCTION function_name [EXPORTING f1=a1 fn=an] [IMPORTING [CHANGING [TABLES f1=a1 fn=an] f1=a1 fn=an] f1=a1 fn=an]

[EXCEPTIONS e1=r1 en=rn ] [ERROR_MESSAGE = E] [OTHERS = o]].

Calling Functions
EXPORTING f1=a1 fn=an
enables the passing of actual parameters to formal input parameters of the function

IMPORTING f1=a1 fn=an


enables the passing of formal output parameters of the function back to the corresponding actual parameters of the calling program

Calling Functions
CHANGING f1=a1 fn=an
enables the passing of actual parameters to the formal parameters and, after processing the system passes the (changed) formal parameters back to the actual parameters

TABLES f1=a1 fn=an


enables the passing of internal tables between actual and formal parameters tables are always passed by reference

Calling Function example


function z_divide. * IMPORTING * EXPORTING endfunction. parameters: num1 type i default 2, num2 type i default 3. data result type p decimals 2. CALL FUNCTION 'Z_DIVIDE' EXPORTING p1 = num1 p2 = num2 IMPORTING p3 = result. write: / num1, '/', num2, '=', result. P1 TYPE I DEFAULT 1 P3 TYPE P P2 TYPE I

p3 = p1 / p2.

2 /

3 =

0.67

Calling Functions
EXCEPTIONS f1=a1 fn=an
functions are defined with exceptions the calling program determines whether and which exceptions it is to handle itself the OTHERS clause covers all exceptions not explicitly specified if an error occurs in the function execution it is either handled in the function or control immediately returns to the calling program (if the exception is specified in the EXCEPTIONS parameter of the call)

ABAP Function Module: FILL_SEATTAB Exceptions NO_ENTRY

Exception defined in function definition Exception condition checked on return from function

call function 'fill_seattab' EXPORTING year = TABLES seattab = EXCEPTIONS no_entry = others =

year itab 01 02.

case sy-subrc. when 1. write No entry. when 2. write Other error. endcase.

function z_divide. * IMPORTING * * EXPORTING P1 TYPE I DEFAULT 1 P2 TYPE I P3 TYPE P

Using raise

* EXCEPTIONS DIV_BY_ZERO if p2 = 0. raise div_by_zero. endif. p3 = p1 / p2. endfunction.

parameters: num1 type i default 2, num2 type i default 3. data result type p decimals 2. CALL FUNCTION 'Z_DIVIDE' EXPORTING p1 = num1 p2 = num2 IMPORTING p3 = result EXCEPTIONS div_by_zero = 01. if sy-subrc = 1. write 'Error: Divide by Zero'. else write: / num1, '/', num2, '=', result. endif.

EditPattern

58

Remote Function Calls


Remote Function Calls offer
an easy way to implement communication between application programs via ABAP function calls do not have to worry about incompatibilities between
hardware platforms operating systems

relieves the programmer from technical considerations of communication protocols

Remote Function Calls


Local Function Call
called function resides on the same machine as the calling program

Remote Function Call


called function resides on a different machine to the calling program
machines must be connected via a network useful for instance if there are many branches/offices where some form of centralised reporting is required

Remote Function Calls


Syntax similar to local function call except for the addition of an extra parameter
DESTINATION dest. machine name

inclusion of the destination parameter alerts the system to the fact that the called function does not reside locally, but on a system whose name is destination machine name

Remote Function Call Example


parameters: date1 type d, date2 type d. data: local_agency(20), local_bookings like sbook occurs 0 with header line. CALL FUNCTION 'GET_LOCAL_BOOKINGS' DESTINATION 'PARIS' EXPORTING from_date = date1 to_date = date2 IMPORTING agency = local_agency TABLES bookings = local_bookings.

Remote Function Calls


Valid destinations are defined in table RFCDES

64

Remotely Callable Functions


Function must be designated as supporting remote function calls in the Remote System
ABAP automatically generates a piece of code that serves as the entry routine (called a stub) for the incoming call stub receives the incoming data and routes it to the desired function function is carried out and results sent back to the user

When an RFC is issued...


Runtime system
converts data to machine independent representation sends the data over the comms line

Partner (remote) system


resolves inconsistencies in terms of
internal data representation different code pages

begins new session


session stays alive as long as the calling program lives

invokes called function


parameters passed by value only

sends data back to the calling system

Handling Communication Errors


Exception conditions
communication_failure
error on the comms line during call execution

system_failure
any runtime error on the partner system
function does not exist function not declared as remotely callable

can add message fld_name to the EXCEPTION clause to receive error message text associated with the error

parameters: date1 type d, date2 type d. data: local_agency(20), sys_msg(80), comms_msg(80), local_bookings like sbook occurs 0 with header line.

CALL FUNCTION 'GET_LOCAL_BOOKINGS' DESTINATION 'PARIS' EXPORTING from_date = date1 to_date = date2 IMPORTING agency = local_agency TABLES bookings = local_bookings EXCEPTIONS system_failure = 1 message sys_msg communication_failure = 2 message comms_msg. case sy-subrc. when 1. write: / System Error:, sys_msg. when 2. write: / Comms Error:, comms_msg. endcase.

Testing Remote Function Calls


The special destination NONE can be used to test remote function calls:
Create function on local machine Activate it as supporting remote calls Call it using 'NONE'

Conclusion
This lecture covered topics associated with
formatting output using the WRITE statement
colours position and length lines and blank lines

subroutines in ABAP
FORM ENDFORM, PERFORM Parameter passing CALL FUNCTION Remote Function Calls (RFCs)

Associated Reading
Textbook Ch 3.4.4 Output Formatting Ch 3.2.12 Subroutines Ch 3.9 Function Modules On Line Help
BC ABAP Users Guide

R/3 LibraryBC..ABAP Workbench


The ABAP Programming Language Modularization Modularizing ABAP Programs Source Code Modules, Subroutines, Function Modules Basic Statements Processing Data Basic form of the WRITE TO Statement Writing Values With Offset Specifications ABAP User Interfaces Lists Creating Simple Lists With The WRITE Statement

Pre-Reading
Textbook
Ch 3.4.2 (p 211): The Events Concept Ch 3.4.3 (p 213): Selections and Parameters
Selection Screens Using Variants

Ch 3.5 (p 243): Interactive Reports

You might also like