Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
The stupid question is the question not asked
 
PerlMonks  

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


Comment on Re: regex'ing source code
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://979024]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (12)
As of 2014-04-24 11:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (565 votes), past polls