Steven Massey wrote at Mon, 10 Jun 2002 08:45:57 +0200: > Hi All > The code I have written below works, and yes I could leave it at that..
Oh, I think you shouldn't. Your code isn't very readable and thats in fact at least important as speed. What does $ff stands for, $gg. Well $gglen is the size of the array @gg, perhaps better written as scalar @gg or $ggsize. Other variables have the name $fin (an end ?!), $T, $H. What shall your code do ? I think it's hard to detect. I'll give downside some examples how you could improve the readability. > 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 > use strict; # doesn't make it slower use warnings; # but better > > $ff="hello fred 12"; my $input_str = 'hello fred 12'; > > @gg=split(//, $ff);$gglen=@gg; OK. You split $$ into the characters. In most cases you won't needed in Perl. There's nearly always a good way to do it with strings directly. > > $hh=substr($ff, ($gglen-1), 1);$fin="n";$val=1; That looks really strange. You take the n-th character of the string $hh, where n depends of the size of @gg - will mean on the number of words in $ff. Seems like you wanted to have in $hh the last character of the string: $last_char = substr $input_str, length $input_str - 1; or the more readable $last_char = $input_str =~ /(.)$/; > > if("$hh" =~ /^\d$/ ) You can simply write $hh =~ /^\d$/. Allthough $hh is the last character of $input_str, so it seems like you wanted to check whether the input_str ends on a number: if ($input_str =~ /\d$/ ) > > $hh=substr($ff, ($gglen-2), 1);$val=2;$fin="n"; Again the same behaviour. Even if it is right, you already have calculated it. $fin seems to be a boolean. Let it be a boolen. E.g., let's say $fin has the name $is_finished. Then you can say $is_finished = 1; or $is_finished = "true" when you say $fin = "y"; And if ($fin eq 'y') is equavilant with if ($is_finished). I could also imagine, that you don't really need that flag. > } else > > $fin="y";$H=substr($ff, 0, ($gglen-1));$T=substr($ff, ($gglen-1), 1); $H will be the total string, that means $H eq $ff. > print "This is text $H and time $T on 1st line\n"; > } > } ... [I stopped here] The best way to achieve good readable code, is to write down the pseudo code for the algorithm and then to translate it into the programming language (what should be easy and without tricks in Perl). BTW, the most readable solution is often quite one of the quickest, too :-) Cheerio, Janek PS: If speed is really so important, have a look to C. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]