Pages

SyntaxHighlighter

Monday, December 19, 2011

Hash Object vs Array Order

I needed to verify that values were in the order specified by a user in a dual selector control object contained in a SAS/AF frame.

My first thought was to load the selected values into a hash object then use a hash iterator object to spin thru the data using its .first() and .next() methods. That worked, but not as I would have expected. The values were all there but they were not in the order entered (natural order) of C, A, D, B but rather in this order: A, C, B, D.

The ordered: 'a' | 'd' (ascending or descending) attribute of the hash declaration would not work in this scenario so I ended up using a one dimensional _temporary_ array. See the below source code and output to better understand what I am describing.


data loadthis ( keep = valx ) ;
  infile datalines eof = alldone ; 
    input valx $ @@ ;
    n + 1 ;
    output ;
  return ;
  
  alldone:
    call symputx( 'acnt', n ) ;
  return ;
 
  datalines ;
C A D B 
;
run ;
 
 
data out_array 
     out_hiter ;
  if 0 then set loadthis /* prime the PDV */;
  keep valx ;
 
  /* load hash object and hash iterator object */
  declare hash h(dataset:'loadthis') ;
  declare hiter hi( 'h' ) ;
  h.definekey( 'valx' ) ;
  h.definedone() ;
 
  /* dimension and populate array */
  array aval[ &acnt ] $ _temporary_ ;
  do until ( eof ) ;
    set loadthis end = eof ;
    rc + 1 ;
    aval[ rc ] = valx ;
  end ;
 
  /* output array */
  do rc = 1 to &acnt ;
    valx = aval[ rc ] ;
    output out_array ;
  end ;
 
  /* output hash object and hash iterator object */
  rc = h.output( dataset:'out_hash' ) ;
  rc = hi.first() ;
  do while( rc = 0 ) ;
    output out_hiter ;
    rc = hi.next() ;
  end ;
 
  stop ;
run ;

Click on image for larger version

No comments:

Post a Comment