Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: regex'ing source code

by muba (Priest)
on Jun 29, 2012 at 00:38 UTC ( #979024=note: print w/replies, xml ) Need Help??

in reply to regex'ing source code

It's not that complex. Just split your lines on tab characters, using split( /(\t)/, $line ). Those parens around \t make sure the tabs themself will be included in the elements of split, too. From there on, it's simple: print out every piece that's not a tab character, and keep track of how many characters you've printed so far. If you eventually do run into a tab character, you just print enough spaces to end up at a tab boundary. To make sure things keep running smoothly, you want to make sure that those spaces also count for the number of characters printed so far.

Still sounds complicated? This is all it takes.

use strict; use warnings; my @lines = map {s/@/\t/g; "$_\n"} split(/\n/, << 'EOF'); @foo bar baz quux @foo bar baz quux foo@bar baz quux foo @bar baz quux foo bar@baz quux foo bar @baz quux EOF my $tabwidth = 8; for my $line (@lines) { my $pos = 0; for my $part (split/(\t)/,$line) { if ($part eq "\t") { my $spaces = " " x ($tabwidth - ($pos % $tabwidth)); $pos += length($spaces); print $spaces; } else { $pos += length $part; print $part; } } } __END__ foo bar baz quux foo bar baz quux foo bar baz quux foo bar baz quux foo bar baz quux foo bar baz quux

Replies are listed 'Best First'.
Re^2: regex'ing source code
by zuma53 (Beadle) on Jun 29, 2012 at 02:58 UTC
    Ah, that missing tidbit of info!

    After the post, it dawned on me about using split. But then I realized that split spits out the split phrase. I never knew about the paren expression before. So much still left to learn about Perl.

    Thanks for the example!

      Well, even if split didn't had that handy bit of also returning the things it captured, you could've gone my @parts = $line =~ m/(\t|[^\t])/g;, which does essentially the same. With that regex you tell perl, "gimme an array of all tabs and all sequences of non-tabs."

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://979024]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2018-05-26 14:10 GMT
Find Nodes?
    Voting Booth?