CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Calculate the width of underscores in group

 



gprakash
New User

Aug 6, 2014, 3:26 AM

Post #1 of 4 (655 views)
Calculate the width of underscores in group Can't Post

Hi,
I need to calculate the width of the underscores which are in groups. Need to ignore the single underscore.Please suggest me a solution.

Expected Output:
ch15_fg001 ch15 _ fg001<emphasis role="fill" width="6.2mm"\/>Match the endocrine word<emphasis role="fill" width="15.5mm"\/>parts with <emphasis role="fill" width="9.3mm"\/> their definitions

I tried the following:

use warnings;
my $x = "ch15_fg001 ch15 _ fg001__Match the endocrine word_____parts with ___ their definitions";
my $y = "3.10";
my ($x1,$x2,$x3,$out);

while ($x =~ m/([_]+)/g){
$x1 = $1;
$x2 = length($x1);
$x3 = $x2*$y;
if ($x2 > 1){
$x =~ s/$x1/<emphasis role="fill" width="${x3}mm"\/>/g;
}}
print "$x\n";


Laurent_R
Veteran / Moderator

Aug 6, 2014, 10:10 AM

Post #2 of 4 (637 views)
Re: [gprakash] Calculate the width of underscores in group [In reply to] Can't Post

It would be nice if you used code tags to keep proper format to your code, and also if you used meaningful variable names.

In this line:

Code
while ($x =~ m/([_]+)/g){

the sqare brackets are not needed: they create a character class with just one character in it which is useless.

You could have instead:

Code
while ($x =~ m/(_+)/g){

but since you don't want to match single underscores, you might as well have this:

Code
while ($x =~ m/(__+)/g){

which will match groups of at least two underscores.

Asides from that, you are not saying in which respect your script does not do what you want (fails? wrong output? wharever else?). Please tell us that, it will be easier for us to help you.

Please try to post correctly formated code (with the code tags) and, if possible with meaningful variable names. This would go a long way toward making your intentions clearer for both yourself and the other readers.


Zhris
Enthusiast

Aug 6, 2014, 10:00 PM

Post #3 of 4 (626 views)
Re: [gprakash] Calculate the width of underscores in group [In reply to] Can't Post

You can also use a substitution operation alone. The e modifier evaluates the right hand side (replacement) as an expression instead of a string.


Code
$x =~ s/(__+)/'<emphasis role="fill" width="' . length($1)*$y . 'mm"\/>'/eg;



(This post was edited by Zhris on Aug 6, 2014, 10:02 PM)


gprakash
New User

Aug 7, 2014, 5:03 AM

Post #4 of 4 (616 views)
Re: [Zhris] Calculate the width of underscores in group [In reply to] Can't Post

Thank you for the help. I got the output correctly.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives