Perl help needed

dsfunk

Golden Member
May 28, 2004
1,246
0
0
I need to translate ^12 to twelve blank spaces. The carat and the following two digits translated into the number of spaces that the two digits says.

Chris^8Webber

translates to

ChrisWebber

for every line, multiple times per line
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
$string = "^12text^5"; # Or whatever string you want.... Chris^8Webber, for example.

$string =~ s/\^(\d+)/sprintf("%$1s")/ge;
 

dsfunk

Golden Member
May 28, 2004
1,246
0
0
sweet, thanks notfred

one problem I have with that

There might be a numeric field after the ^## so I can't use the d+ I think. What do I use?
 

dsfunk

Golden Member
May 28, 2004
1,246
0
0
Originally posted by: notfred
I wonder why I answer questions when no one plans on reading my answers.


I didn't get back to it until this morning.
 

dsfunk

Golden Member
May 28, 2004
1,246
0
0
ok thanks.

almost there.

I need to trim the leading zero off of that, if there is one, before it goes into %$1s
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
Did you change the line so that it looks for two digits instead of any arbitrary number of digits, and now you're padding single digit numbers with a zero? (That's what it sounds like)

If so:

$string =~ s/\^(\d{2})/sprintf("%".int($1)."s")/ge;

Of course, you can use \d{1,2} instead of \d{2} if you want to match either 1 or 2 digits, instead of only exactly two.
 

dsfunk

Golden Member
May 28, 2004
1,246
0
0
Another related question...If I also needed to print this to a webpage, what's wrong with this?


$line =~ s/\^(\d{2})/for ( my $counter=0; $counter<($1); $counter++){print "nbsp;";}/ge;

note nbsp does have an ampersand in front
 

dsfunk

Golden Member
May 28, 2004
1,246
0
0
I get the correct number of nbsp, but they are all at the beginning of the line, not replacing the ^##