We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Foreach on a string.

cide
cide asked
on
Medium Priority
318 Views
Last Modified: 2010-03-05
Is there anyway to do a foreach loop on a string?  Or a similar loop.  So it loops through once for every char in the string.  So in the word "hello" it would loop 5 times and $k would hold the letter for which it's going through the loop for.
Thanks in Advance.
Comment
Watch Question

Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
#also,
for( $str=~/(.)/sg ){ print; }
while( $str=~/(.)/sg ){ print "$1\n"; }
#if you want to change each character:
$str=~s/(.)/$change{$1}/gs;
#if you want the ord of each character:
for( 0..length($str)-1 ){ $k = vec($str,$_,8) }
for( unpack'C*',$str ){print $_,"\n" }

Author

Commented:
Thanks,  I don't actually need to change the string so that works perfectly.  I was origionally doing it the second way you said, but the first way is better.

Author

Commented:
How would I use split to make it every three characters? I.E.  it would split 1000000 into three elements in an array 1, 000 and 000 and 999999 would split into 999 and 999.
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
For every three characters, /(...)/sg may be easier than using split
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
Wait a minute, in your 1,000 example, the dirst element doesn't have three characters.
Perhaps you want "How can I output my numbers with commas added?" from perlfaq5?

Author

Commented:
Sort of but I don't want commas added.  exactly like the comma thing but I don't want commas.  Where the comma should be a new element should start.
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
How about:
reverse map{''.reverse $_} (reverse($str)=~/(\d{1,3})/g);
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.