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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to reverse a string *revisited*
by PodMaster (Abbot) on Nov 11, 2003 at 09:54 UTC | |
|
Re: How to reverse a string *revisited*
by Zaxo (Archbishop) on Nov 12, 2003 at 01:03 UTC | |
by Abigail-II (Bishop) on Nov 12, 2003 at 01:08 UTC | |
|
Re: How to reverse a string *revisited*
by liz (Monsignor) on Nov 11, 2003 at 09:41 UTC | |
by Abigail-II (Bishop) on Nov 11, 2003 at 10:09 UTC | |
by Anonymous Monk on Nov 11, 2003 at 10:08 UTC | |
by ihb (Deacon) on Nov 14, 2003 at 23:51 UTC | |
|
Re: How to reverse a string *revisited*
by Aristotle (Chancellor) on Nov 11, 2003 at 20:13 UTC | |
|
Re: How to reverse a string *revisited*
by Anonymous Monk on Nov 11, 2003 at 23:40 UTC |