Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: How to replace Tab with spaces not altering postion

by petral (Curate)
on Oct 10, 2002 at 15:11 UTC ( #204199=note: print w/replies, xml ) Need Help??

in reply to How to replace Tab with spaces not altering postion

> perldoc -q tabs Found in /usr/local/lib/perl5/5.6.1/pod/perlfaq4.pod How do I expand tabs in a string? You can do it yourself: 1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e; Or you can just use the Text::Tabs module (part of the standard +perl distribution). use Text::Tabs; @expanded_lines = expand(@lines_with_tabs); >
and this from perlop:
Occasionally, you can't use just a `/g' to get all the changes to occur that you might want. Here are two common cases: # put commas in the right places in an integer 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g; # expand tabs to 8-column spacing 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
And this has been in the perl man page since perl1!
print "\et" x ($tab/8), ' ' x ($tab%8); # tab over


Replies are listed 'Best First'.
Re^2: How to replace Tab with spaces not altering postion
by Aristotle (Chancellor) on Oct 11, 2002 at 21:45 UTC

    The problem is it's using $` which incurs a huge performance penalty.

    Here's another OWTDI:

    $_ = join "", map { $_ . " " x (8 - length() % 8) } split /\t/, $_, -1;
    Update: blakem points out that this code is broken. It will pad all parts of the string to a multiple of 8, including the last one. Getting it not to is disappointingly awkward..
    $_ = join "", do { my @bits = split /\t/, $_, -1; (map { $_ . " " x (8 - length() % 8) } @bits[0..$#bits-1]), $bits[ +-1] };
    (Update is untested.)

    Makeshifts last the longest.

      join "", map{ $_ . (/\n/ ? "" : " " x (8 - length() & 7)) } split /\t/

        $_ = "You\tare\tmaking\ttoo\tmany\tassumptions...";

        Makeshifts last the longest.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://204199]
[LanX]: Let's Make PerlMonks Great Again!
[holli]: but you know what? i don't think i'd fancy that. I like PM as it is.
[holli]: Alone the chatterbox and everybody writes his own cb client tradition
[LanX]: there was a guy who tried to steal the concept and build an own monastery ...
[LanX]: yeah PM is very emacsy ;-)
[LanX]: I think tobyink was on a good track with his redesign, pitty the pmdevs/gods didn't try to continue the approach of a modern responsive design
[holli]: *sigh* why has there to be drama in such a thread?
[LanX]: ?
[holli]: Re^2: Let's Make PerlMonks Great Again! -- suggestions and dreams - STFU and write code already (start already)

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2017-11-20 19:40 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (292 votes). Check out past polls.