Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Replace multiple tabs with spaces at start of a string

by mavericknik (Sexton)
on May 16, 2017 at 22:44 UTC ( #1190410=perlquestion: print w/replies, xml ) Need Help??

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

Hello monks, I have a quick regex question. What would be the best way to replace multiple tabs at the start if a line with spaces. I want to replace each tab with 4 spaces, and there are a variable number of tabs at the start of each line. My thought was to replace each tab with another garbage value recursively and the replace that garbage value with 4 spaces on another regex. Anymore efficient way of doing this?
  • Comment on Replace multiple tabs with spaces at start of a string

Replies are listed 'Best First'.
Re: Replace multiple tabs with spaces at start of a string
by choroba (Cardinal) on May 16, 2017 at 22:52 UTC
    Why can't you replace the tabs directly?
    s/^(\t+)/' ' x (4 * length $1)/e;

    The number of spaces will be four times the number of tabs.

    Or, without /e :

    $s =~ s/(^|\G)\t/ /g;

    Replace a tab with 4 spaces if it's at the start of the string or after a previously replaced tab.

    Update: The latter could be simplified to

    $s =~ s/\G\t/ /g;

    as the "last match" is initially set to the beginning of the string.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      ++

      With the /m modifier, the first solution also works on multiline input: print $_ and print s/(^|\G)\t/____/mgr for "\tHello\t\n\t\tWorld\t!\n\t!\n";

      Thank you very much! I was not aware of \G in perl, I will look into it.
      what is the meaning of the \G there??
        Anchor where to start for next match.

        The \G anchor matches at the point where the previous//g match left off. \G allows us to easily do context-sensitive matching... perlretut

Re: Replace multiple tabs with spaces at start of a string
by tybalt89 (Monsignor) on May 16, 2017 at 23:01 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1190410 use strict; use warnings; my $input = <<END; | | | | | | | | ! ! first line \t\tsecond line \t\t\tthird line \tfourth line \t\tfifth line \t\tline with\t\tin the middle last line END open my $fh, '<', \$input or die "$! opening file"; while(<$fh>) { s/\G\t/ /g; print; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2022-11-28 12:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?