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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

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



Aug 6, 2014, 3:26 AM

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

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";

Veteran / Moderator

Aug 6, 2014, 10:10 AM

Post #2 of 4 (1247 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:

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:

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

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

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.


Aug 6, 2014, 10:00 PM

Post #3 of 4 (1236 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.

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

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


Aug 7, 2014, 5:03 AM

Post #4 of 4 (1226 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