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

Replacing string with its length in Regex

by Brovnik (Hermit)
on Jul 27, 2001 at 16:25 UTC ( [id://100355]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

Brovnik has asked for the wisdom of the Perl Monks concerning the following question:

I have a sub which converts e.g.
_________XX_X_XX_________ => 2,1,2 __________XXXXX__________ => 5 ____XXXX___XXX__XXXXX____ => 4,3,5
Spec: output is comma separated list of run lengths of the 'X' parts.

The sub is :

sub template { my $r = shift; $r =~ s/^_+//; $r =~ s/_+$//; $r =~ s/_+/_/g; return join ',', map { length($_) } split(/_/,$r); }
Is there a Regex way of doing the last line ?
I'd like to be able to do e.g.
s/(X+)/length($1)/g;
But this if course doesn't do what I need.
--
Brovnik

Replies are listed 'Best First'.
Re: Replacing string with its length in Regex
by bikeNomad (Priest) on Jul 27, 2001 at 16:34 UTC
    Why not just:

    my $s = s/_*(X+)_*/length($1) . ','/ge; $s =~ s/,$//;
      even simpler:
      $r =~ s/(^_+|_+$)//g; $r =~ s/_+/,/g; $r =~ s/(X+)/length$1/ge;
        p

Re: Replacing string with its length in Regex
by japhy (Canon) on Jul 27, 2001 at 16:40 UTC
    You can execute code in the right-hand side of a substitution, by supplying the /e modifier.
    s/(X+)/length $1/eg;

    _____________________________________________________
    Jeff japhy Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Replacing string with its length in Regex
by merlyn (Sage) on Jul 27, 2001 at 18:00 UTC
      Not homework honest.

      It is part of a Nonogram Solver/manipulator. This sub is part of the file loader. I know that nonogram solvers have been given as homework in other places, and I wrote one in C++ some time ago, but thought I would rebuild it in Perl for fun.

      This site gives more on Nonograms (also know as Paint by Numbers).
      --
      Brovnik

        Wow, so there is a name for the puzzles in picross! I take it the idea is to generate the number hints to a puzzle from an ascii bitmap?

        'The fickle fascination of and Everlasting God' - Billy Corgan, The Smashing Pumpkins

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://100355]
Approved by root
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.