ibmi-brunch-learn

Announcement

Collapse
No announcement yet.

Scan

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Scan

    I have an address field
    Field 1
    123 main St MD
    14 South St PA

    i want to start to the right of the field and get the first 2 characters that are not blanks, and put MD and PA in a field, how would i do that ? with a scan?

  • #2
    dcl-s temp varchar(60);

    dcl-s state char(2);

    temp = %TrimR(field1);

    EvalR state = temp;

    Or simply ... but perhaps less obviously

    EvalR state = %TrimR(field1);

    Comment


    • #3
      You left out a bunch of information that would be really useful, such as... how is the address field defined? Is this a fixed-length field that'll have unnecessary blanks at the end, or is it something like a varying/varchar that wouldn't? How do you know that the state code will always be the last 2 non-blank characters? Is it really the last 2 that you always want, or is it whatever is in the last "word" of the address?

      So I guess I'll answer this based on exactly what you asked... and I'll try to write a subprocedure that'll handle any sort of field as input.

      The basic process of getting the last 2 non-blank characters is very simple:

      1) Find the length without the trailing blanks.
      2) Substring starting at the length (from step 1) minus 1, and take a length of 2.

      Of course, you should also account for the situation where there isn't 2 characters in the string, because if the length - 1 results in zero or a negative number, the %subst BIF would trigger an error. Also, I'd wrap it up in a subprocedure so you don't have to repeat the code everywhere you need it.

      With that in mind, off the top of my head, I'd do this:
      Code:
      **free
      ctl-opt dftactgrp(*no);
      
      dcl-s field1 char(100);
      dcl-s field2 like(field1);
      dcl-s state  char(2);
      
      field1 = '123 main St MD';
      field2 = '14 South St PA';
      
      state = getLast2(field1);
      dsply state;
      state = getLast2(field2);
      dsply state;
      
      *inlr = *on;
      
      
      dcl-proc getLast2;
      
        dcl-pi *n char(2);
          addr varchar(100) options(*trim) const;
        end-pi;
      
        dcl-s len int(10);
        dcl-s state char(2) inz('  ');
      
        len = %len(addr);
        if len > 2;
          state = %subst(addr: len - 1: 2);
        endif;
      
        return state;
      
      end-proc;

      Comment


      • #4
        Oh, that's true... EVALR would do it as an alternative to %SUBST... Though, I find that EVALR (much like MOVE/MOVEL) can be hard for non-RPGers to follow.

        Comment

        Working...
        X