You couldn't use a better source than this book!
You are right, you need to move the iterator:
If an associated hash iterator is pointing to the keyvalue, then the REMOVE method will not remove the key or data from the hash object. An error message is issued. |
All good, it makes perfect sense now! 🙂
Methinks your solution is fine. This:
rc=hi.last();
rc=hi.next();
is also the right thing to do if you just want a simple means to make sure you don't get the iterator locking error.
The only slight inaccuracy in " the object is locked by an iterator" is that the iterator locks not the whole table but all the items within the same-key group where the iterator currently dwells. Of course, when you want to purge the whole thing with CLEAR, i.e. every key group,the iterator pointer must be moved completely out of the table before calling CLEAR - and the two calls above (or first/prev - doesn't matter) are the simplest and fastest way of achieving it. You can figure it all out mighty quickly by playing a little bit with this piece of code:
data _null_ ;
dcl hash h (multidata:"y", ordered:"a") ;
h.definekey ("k") ;
h.definedone () ;
dcl hiter ih ("h") ;
do k = 1, 2, 2, 3, 3, 3 ;
h.add() ;
end ;
do i = 1 to 3 ;
_n_ = ih.next() ;
end ;
h.remove (key:1) ; * works ;
* h.remove (key:2) ; * fails ;
h.remove (key:3) ; * works ;
run ;
You'll invariably see that getting the iterator out of a same-key group frees it for removal. Note that ordering the table is a must, as otherwise you cannot control when the iterator gets out of the same-key group. And, as said above, getting it out of the table altogether (above, it would happen if the upper bound of the DO I loop were 7) frees them all. But if the latter is the goal, why enumerate the whole table (as astonishingly ill-advised in one of SAS Support tech notes, especially if the table is big) if you can just use the pair of last/next or first/prev.
Kind regards
Paul D.
@hashman Thank you for the explanation. Makes sense.
Do you happen to have a link to that SAS Support tech note?
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.