23
Sat, Nov
1 New Articles

TechTip: Entering Quotes in CL Variables — A Better Way?

CL
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Is there a foolproof way to enter single quotes (') in a Control Language (CL) program variable without having to double them?

Nearly everyone knows that to embed a quotation mark in a CL variable you have to double it. To putNAME='SMITH'in a variable, you have to enter'NAME=''SMITH'''. Enter an uneven number of quote marks and the CL prompter will attempt, and nearly always fail, to fix if for you, which can make entering code challenging and sometimes frustrating. What if we could use a double quote ("), and then easily replace each with a single quote programmatically?

A recent discussion got me wondering if there was, indeed, an easier way. I did some coding, research, and experimentation and came up with two experimental commands:

  • FIXQTE replaces each double quote character in a CL variable with a single quote character.
  • RPLSTR replaces one string in a CL variable with another string.

This article documents my findings and alternative ways to put single quotes in CL variables.

Article definitions:

  • "Quote" means one character (') which is sometimes described as an apostrophe or a tick.
  • "Double quote" also means one character ("), which is sometimes described as a quotation mark. Do not confuse it with two single quotes ('').

A Problem Example

Here's an example of the quote conundrum. You are trying to put quotes around a variable, perhaps to use it in an SQL WHERE statement:

(&sel *bcat '''' *bcat &name *bcat '''')

Miscount the single quotes and the CL prompter might helpfully change it to this:

('(&SEL *BCAT '''''' *BCAT &NAME *BCAT '''''''')')

What's the best approach to avoid this confusion while making such entries? A discussion of possible approaches follows.

Approach 1: Live with It and Code Carefully

Understand when you need to double the quote, and then enter code carefully. To evaluate ease of entry and readability, I created a test CL program T1 with two entered parameters (Figure 1, below). The program has to build an SQL statement with a "where" clause from the parameters, run the SQL, and display the results. The input file is on virtually all IBM i machines, if you want to compile and run it.

Calling the program thus…

call t1 ('ON' 'NY')

creates an SQL statement in a variable that has embedded quotes, like this:

create table qtemp/zz as (select * from qiws/qcustcdt

where upper(lstnam) like '%ON%' and state='NY'

order by lstnam) with data

Running it displays two records:

0001.00 pgm parm(&name &state)                                        

0002.00 dcl &name *char 10 'ON'                                      

0003.00 dcl &state *char 2 'NY'                                      

0004.00 dcl &sql *char 512 'create table qtemp/zz as ('              

0005.00 dcl &sel *char 100 'select * from qiws/qcustcdt where '      

0006.00 dcl &whr *char 256                                            

0007.00 dcl &end *char 50 'order by lstnam) with data'              

0008.00 chgvar &whr ('upper(lstnam) like ''%' *tcat &name *tcat '%''')

0009.00 chgvar &whr (&whr *tcat 'and state=''' *tcat &state *tcat '''')

0010.00 chgvar var(&sql) value(&sql *tcat &sel *bcat &whr *bcat &end)

0011.00 sndmsg &sql tousr(*requester)                                

0012.00 runsql &sql commit(*none)                                      

0013.00 runqry *none qtemp/zz                                        

0014.00 dltf qtemp/zz                                                

0015.00 endpgm                                                        

Figure 1: Program T1, coded carefully

Where you can come undone is entering line 8, building the &whr variable. On the right side, the string must be in quotes, but we need to embed quotes around the &name field, as well as around the % sign at each end of the &name value. These quotes, inside the enclosing outer quotes, have to be doubled. Similarly with adding the state selection in line 9. But, by being careful, you can get it done.

Approach 2: Quote Variables Separately

First put quotes around each parameter value, and use these quoted variables in the right side. We introduce two new longer variables to hold the quotes on each end of the variable. And for name, we also need space for the % signs. We create program T2 by making the changes in Figure 2, below, to program T1.

0008.00 dcl &qname *char 14                                

0009.00 dcl &qstate *char 4                                

0010.00 chgvar &qname ('%' *tcat &name *tcat '%')        

0011.00 chgvar &qname ('''' *tcat &qname *tcat '''')    

0012.00 chgvar &qstate ('''' *tcat &state *tcat '''')    

0013.00 chgvar &whr ('upper(lstnam) like' *bcat &qname)  

0014.00 chgvar &whr (&whr *tcat 'and state=' *tcat &qstate)

Figure 2: Changes to T1 to make program T2

This makes lines 13 and 14 simpler to enter and easier to read, and we've avoided embedding quotes in the right side. The downside is two extra lines of code for each quoted variable.

Approach 3: Use a Variable for the Quote

Declare a single character viable that is a quote and use that where you need to embed a quote. Change program T1 as in Figure 3 below to create program T3.

0008.00 dcl &qt *char 1 ''''   /* single quote */            

0009.00 chgvar &whr ('upper(lstnam) like ' *tcat &qt *tcat '%')

0010.00 chgvar &whr (&whr *tcat &name *tcat '%' *tcat &qt)    

0011.00 chgvar &whr (&whr *bcat 'and state=' *tcat &qt)      

0012.00 chgvar &whr (&whr *tcat &state *tcat &qt)            

Figure 3: Changes to T1 to make program T3

It is harder to miscount quotes, but to me, it seems less readable.

Approach 4: A Combination of 2 and 3

This means minor changes to T2 to make program T4, as in Figure 4.

0008.00 dcl &qname *char 14                      

0009.00 dcl &qstate *char 4                      

0010.00 dcl &qt *char 1 ''''   /* a single ' */  

0011.00 chgvar &qname ('%' *tcat &name *tcat '%')

0012.00 chgvar &qname (&qt *tcat &qname *tcat &qt)

0013.00 chgvar &qstate (&qt *tcat &state *tcat &qt)

Figure 4: Changes to T2 to make program T4

This adds a little to the readability and decreases the chance of miscounting quotes.

Approach 5: Use the FIXQTE Command

Where you need two quotes to create a single embedded quote, enter a single double quote instead and convert to single quotes at run time. We create program T5 by changing T1 as in Figure 5 below:

0008.00 chgvar &whr ('upper(lstnam) like "%' *tcat &name *tcat '%"')

0009.00 chgvar &whr (&whr *tcat 'and state="' *tcat &state *tcat '"')

0010.00 chgvar &sql (&sql *tcat &sel *bcat &whr *bcat &end)

0011.00 fixqte &sql                                                  

Figure 5: Changes to T1 to make program T5

The FIXQTE command in line 11 changes all occurrences of " to ' in the &sql variable. It eases entry and improves readability.

Approach 6: Use FIXQTE and Quote Variables Separately

This is a minor tweak of program T2. The changes are shown in Figure 6.

0010.00 chgvar &qname ('%' *tcat &name *tcat '%')        

0011.00 chgvar &qname ('"' *tcat &qname *tcat '"')      

0012.00 chgvar &qstate ('"' *tcat &state *tcat '"')      

0013.00 chgvar &whr ('upper(lstnam) like' *bcat &qname)  

0014.00 chgvar &whr (&whr *tcat 'and state=' *tcat &qstate)

0015.00 chgvar &sql (&sql *tcat &sel *bcat &whr *bcat &end)

0016.00 fixqte &sql                                      

Figure 6: Changes to program T2 to make program T6

My Conclusion

After coding and experimenting, I've decided that coding embedded quotes in CL variables may always be tricky. Having a clear view of the string you are building is important so you know where embedded quotes are needed.

For most of my career, I've tended to use Approach 2, where I put the quotes around the variable before building the final string. Sometimes I've felt clever and opted to code carefully, and often pounded the keyboard when I miscounted the quotes. FIXQTE should reduce such pounding and also improve readability if you choose not to quote variables separately.

You may have another approach to embedding quotes that you'd like to share. I'm all ears.

 The FIXQTE and RPLSTR Commands

These both call the same RPG program that replaces a string in a CL program character variable with another string. FIXQTE simply defaults to replacing " with '. RPLSTR allows you to specify the from and the to strings.

A RPLSTR example:

0001.00 pgm                                              

0002.00 dcl &logmsg *char 50 ('Using \TorP\ library list')

0003.00 rplstr (&LOGMSG) FROM('\TorP\') TO(PRODUCTION)  

0004.00 sndmsg &logmsg tousr(*requester)                

0005.00 endpgm                                          

A call results in this message being sent:

Using PRODUCTION library list

Code

The code for the commands, the program, and the sample approach code is available for download here. For completeness, I have included help for the commands. The RPG program uses the %SCANRPL function introduced in V7R1 and tested on V7R4.

Sam Lennon

Sam Lennon is an analyst, developer, consultant and IBM i geek. He started his programming career in 360 assembly language on IBM mainframes, but moved to the AS400 platform in 1991 and has been an AS400/iSeries/i5/IBM i advocate ever since.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: