Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

simplifying substitution

by Konabob (Initiate)
on Mar 08, 2021 at 06:24 UTC ( #11129317=perlquestion: print w/replies, xml ) Need Help??

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

In the following code, I am inserting 2 tab characters \t\t after every instance where a 2 digit number in a long string is preceded by 2 spaces and followed by a space.
I am using substitution, but wonder if there is a simple one-liner that will add the \t\t for any number between 10 and 99.

$all =~ s/ 95 / 95\t\t/g; $all =~ s/ 80 / 80\t\t/g; $all =~ s/ 75 / 75\t\t/g; $all =~ s/ 70 / 70\t\t/g; $all =~ s/ 65 / 65\t\t/g; $all =~ s/ 60 / 60\t\t/g; $all =~ s/ 50 / 50\t\t/g; $all =~ s/ 40 / 40\t\t/g; $all =~ s/ 33 / 33\t\t/g;

Replies are listed 'Best First'.
Re: simplifying substitution
by swl (Vicar) on Mar 08, 2021 at 07:13 UTC

    Maybe this?

    $all =~ s/  ([1-9][0-9]) /  $1\t\t/g;

      Maybe my perl version is different, but I can never get away with using actual spaces like that on the match side--I'd have to represent them...something like this:

      $all =~ s/([ ]{2}[1-9][0-9])[ ]/$1\t\t/g;

      If running strictly on English and there were no possibilities or no issue with encountering numbers like '04' which had to be handled differently, the code could be a mite simpler:

      $all =~ s/([ ]{2}\d\d)[ ]/$1\t\t/g;

      Blessings,

      ~Polyglot~

        Without the /x modifier, a space should match literally. What's the output of
        perl -lwe 'print qq( $]) =~ s/ /v/r'
        (use double quotes instead on MSWin)

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

        Thanks to all of you, for your contributions! Since my script will be dealing strictly with English text, I decided to try "$all =~ s/( {2}\d\d) /$1\t\t/g;" first, and it seems to do the trick!
        Aloha, and stay safe!

Re: simplifying substitution
by Anonymous Monk on Mar 08, 2021 at 15:19 UTC

    Since you are using at least Perl 5.10, you could do

    s/  [0-9]{2}\K /\t\t/g

    which retains everything before the \K.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11129317]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2021-10-28 01:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (95 votes). Check out past polls.

    Notices?