I was about to ask the question how to reverse a string but luckily (nah - because of discipline), i searched PM before: This node explains how you can achieve it. Why didn't it work for me? Well because Perl tricked me badly.
Nothing happened. Scalar context scalar context... $str is a scalar no? ;-)my $str = "Hello"; print reverse $str;
Then I had a look at the Perl Cookbook and the solution "processing a string one character at a time" involved the creation of a list, which isn't acceptable because I have to reverse whole files (can do so in memory, but not with the file in a scalar AND splitted each byte in a list).
I then ended up with a solution that worked but instantly didn't feel perlish:
Ugly isn't it. Simple things should be simple. Therefore there MUST be a better solution in Perl.sub rev_scalar { my $data = shift; my $i; my $tmp; for($i = 0; $i < int(length($$data)/2); $i++) { $tmp = substr($$data,$i,1); substr($$data,$i,1) = substr($$data,-($i+1),1); substr($$data,-($i+1),1) = $tmp; } }
reverse is this solution, but I didn't see it because I tested it within print which - I suppose - puts the whole thing into list context.
Ah well. So a print scalar(reverse $str); should work. And it does. And now is time to admit, that whatever skills I may have reached in Perl, I still haven't sufficient intuition about the list/scalar context thing.
Bye
PetaMem All Perl: MT, NLP, NLU
In reply to How to reverse a string *revisited* by PetaMem
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |