Hi,

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.

Of course I tried a
my $str = "Hello"; print reverse $str;
Nothing happened. Scalar context scalar context... $str is a scalar no? ;-)

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:

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; } }
Ugly isn't it. Simple things should be simple. Therefore there MUST be a better solution in Perl.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.