Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Alignment of text using regex

by imp (Priest)
on Jan 16, 2007 at 18:13 UTC ( [id://594947]=note: print w/replies, xml ) Need Help??


in reply to Alignment of text using regex

While you can do this with a regex it wouldn't be as easy to maintain as an unrolled version using split and printf.

Contrast this:

use strict; use warnings; $/ = undef; my $data = <DATA>; $data =~ s{^(.*?)\|}{sprintf '%-45s', $1}meg; print $data; __DATA__ ABCDEFGHIJKLMNOPQRST|1234 ABCDEFGHI|12345 ABCDE|1234 ABCDEFGHIJKL|123 ABCDEFG|123456 ABCDEFGHIJKLMNO|12
With:
use strict; use warnings; while (my $line = <DATA>) { my ($lhs,$rhs) = split /\|/, $line, 2; printf "%-45s%s", $lhs,$rhs; } __DATA__ ABCDEFGHIJKLMNOPQRST|1234 ABCDEFGHI|12345 ABCDE|1234 ABCDEFGHIJKL|123 ABCDEFG|123456 ABCDEFGHIJKLMNO|12

Replies are listed 'Best First'.
Re^2: Alignment of text using regex
by jdporter (Paladin) on Jan 16, 2007 at 18:38 UTC

    How about the best of both worlds?

    while(<DATA>) { s(\|){ ' ' x (45-pos) }e; print }
    A word spoken in Mind will reach its own level, in the objective world, by its own weight

      Your dark arts frigten me.

      -Paul

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (None)
    As of 2024-04-18 23:42 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found