Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: palindrome using regular expressions

by Hofmator (Curate)
on Oct 10, 2006 at 11:28 UTC ( [id://577377]=note: print w/replies, xml ) Need Help??


in reply to palindrome using regular expressions

This uses the recursive definition of a palindrome:
  • A single letter is a palindrome.
  • Or a palindrome consists of a single letter, an (optional) palindrome and the same single letter.

As for other solutions, there is of course the non-regex way of doing join '',reverse split //, $_ eq $_ but that is probably not what you are looking for.

Note that my $r = "(??{\$palindrome})"; is equivalent to my $r = '(??{$palindrome})';, there is no reference involved (as I thought at first glance).

Update: Minor typo correction

-- Hofmator

Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: palindrome using regular expressions
by reneeb (Chaplain) on Oct 10, 2006 at 12:01 UTC
    You don't have to split. reverse can also handle strings:

    #!/usr/bin/perl use strict; use warnings; my $palindrome = 'lagerregal'; my $check = reverse $palindrome; print "yes\n" if $check eq $palindrome;
    (see perldoc -f reverse)
      Yes, you are absolutely right. Thanks for the correction.

      In fact, I also thought that reverse worked on strings and so I tried print reverse 'hello' which returns hello. From that I (incorrectly) concluded that it doesn't work ... well, got bitten by list context again, print scalar reverse 'hello' does the job OK :)

      -- Hofmator

      Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        exactly.

        reverse is aware of its context; if you use it in string context ($reverse = reverse ...), it reverses the string; but if you use it in list context (print reverse ... or @array = reverse ..), it reverses the list (and does nothing if the list only has one element

        Best regards,
        perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://577377]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2024-04-25 02:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found