PDA

View Full Version : [perl] converting a string



mickey
20th March 2009, 12:24
Hello,
i have a problem with perl. Se below.


my $v =0;
........................................
if ($_ =~ m/value = (\S+)/) {
$v = $1; // $1 take the right value eg. "e-33"
if ( $v < 1) { # here the error
......................
}
//the file is:
..............
otherString value = e-30 otherString
otherString value = 4e-30 otherString
otherString value = 1e-20 otherString
.........................

I have to extract the value of field "value" in a file a compare it as it was a numerical. But the shell says that $v it's not numeric....

Is it possible?

thanks,

caduel
21st March 2009, 07:38
well, "e-30" is not really a (plain) number, is it?
(are you sure the Perl string to number conversion is not limited to ints?)

maybe the following helps
http://search.cpan.org/~softdia/Data-Str2Num-0.07/lib/Data/Str2Num.pm
or maybe
http://docstore.mik.ua/orelly/perl/cookbook/ch02_02.htm

mickey
24th March 2009, 11:26
I've made a mistake. I have before to extract the value
otherString value = 4 otherString e-30

it's a the end!
I have the string into the variable $_
Let that how can I extract the last part of the line?

thanks,

caduel
25th March 2009, 11:58
sorry, I don't follow you. could you perhaps rephrase that?

mickey
25th March 2009, 12:37
my $v1 =0;
my $v2=0;
........................................
if ($_ =~ m/Content:/) {
$v1 = # I need to extract Value1....
$v2 = # I need to extract Value2....
if ( $v2 < 1) { //this is ok
......................
}
//the file is:
SomeString SomeString
Content:
# blank line
SomeString SomeString SomeString SomeString Value1 Value2
SomeString SomeString Value1 Value2
SomeString SomeString SomeString Value1 Value2
# blank line
SomeString
SomeString SomeString
.........................

As you can see there are some lines that end with two numbers. Is it possible detect only that line and extract the last two values?

thanks,

caduel
26th March 2009, 13:33
my $v1 =0;
my $v2=0;
# match all lines that end with two numbers
# (note: only unsigned integers are matched, not floats like 2.3, -3.4, 2e-3 ...!)
if ($_ =~ m/.*/\s+(\d+)\s+(\d+)\s*$/)
{
$v1 = $1;
$v2 = $2;

if ( $v2 < 1) {
...

If you need to match not only integers the you need to replace the (\d+) by more complicated regexs for whatever numbers you need to match. See, e.g. http://docstore.mik.ua/orelly/perl/cookbook/ch02_02.htm

HTH