[EMAIL PROTECTED] wrote: > Hi All > The code I have written below works, and yes I could leave it at that.. but > I want if possible to write efficient > code as this seems to be what PERL is all about. So any thoughts anyone ?? > > ===================================================== > this code takes a variable containin words and maybe ending in a number, > and > seperates the two >
General Tips Always "use strict" your code and enable warnings Took me some time to get your code organized. Need to indent it better, the if statements seem to have the opening curly missing (may be your mail client is at fault) > > $ff="hello fred 12"; > > @gg=split(//, $ff);$gglen=@gg; > > $hh=substr($ff, ($gglen-1), 1);$fin="n";$val=1; > > if("$hh" =~ /^\d$/ ) $hh does not have to be double quoted here if ($hh =~ /^\d$/) should do Also avoid writing multiple statements in one line, improves readability > > > $hh=substr($ff, ($gglen-2), 1);$val=2;$fin="n"; > } else > > $fin="y";$H=substr($ff, 0, ($gglen-1));$T=substr($ff, ($gglen-1), 1); > print "This is text $H and time $T on 1st line\n"; > } > > if("$fin" eq "n" ) > > if("$hh" =~ /^\d$/ ) > > $hh=substr($ff, ($gglen-3), 1);$val=3; > } else > > $fin="y";$H=substr($ff, 0, ($gglen-2));$T=substr($ff, ($gglen-2), 2); > print "This is text $H and time $T on 2nd line\n"; > } > } > > if("$fin" eq "n" ) > > if("$hh" =~ /^\d$/ > > $hh=substr($ff, ($gglen-4), 1);$val=4; > } else > > $fin="y";$H=substr($ff, 0, ($gglen-3));$T=substr($ff, ($gglen-3), 3); > print "This is text $H and time $T on 3rd line ... $H\n"; > } > } You are assuming that your string if it ends with a number will only be 4 digits wide. if $str is assigned "hello fred 12345" it will print nothing. The multiple if's should actually be written as a loop with the numeric counter used in your substr calls as the index. I would do this like this if ($str =~ m/^([^\d]+)(\d+)$/) { print "text is $1\n"; print "num is $2\n"; } $1 will contain everything from the start of $str that is not a number. perldoc perlre (Read through the section on character classes) $2 will contain the numbers at the end of $str. This ofcourse assumes that the numeric part of $str only occurs at the end of $str. if $str is assigned "hello 12 fred" this regex will fail. Is this what you want? > > > -- > To unsubscribe, e-mail: [EMAIL PROTECTED] > For additional commands, e-mail: [EMAIL PROTECTED] -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]