Perl FAQ 4.35: How do I expand tabs in a string?

Perl FAQ 4.35

How do I expand tabs in a string?

    1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;

You could have written that

    while (s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) {
	# spin, spin, spin, ....
    } 

Placed in a function:

sub tab_expand {
    local($_) = shift;
    1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
    return $_;
} 

This is especially important when you're working going to unpack an ascii string that might have tabs in it. Otherwise you'll be off on the byte count. For example:

$NG = "/usr/local/lib/news/newsgroups";
open(NG, "< $NG") || die "can't open $NG: $!";
while () {
    chop;  # chomp would be better, but it's only perl5
    # now for the darned tabs in the newsgroups file
    1 while s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
    ($ng, $desc) = unpack("A24 A*", $_);
    if (length($ng) == 24) {
        $desc =~ s/^(\S+)\s*//;
        $ng .= $1;
    } 


Other resources at this site: