in reply to how to split a string at [ ?

Another regex approach, with broader matching and some negative cases. See Regexp::Common.

c:\@Work\Perl\monks>perl -wMstrict -le "use Regexp::Common; ;; my @records = ( 'BCInletTemperature = 90[C]', 'BCInletTemperature = 33.56[C]', 'Whatever = -.012[C]', 'Wrong = 90 [C]', 'AlsoWrong = 9.0.1[C]', ); ;; for my $record (@records) { printf qq{'$record' -> }; my $got_temp = my ($temp) = $record =~ m{ = \s+ ($RE{num}{real}) \[ }xms; if ($got_temp) { print qq{temp '$temp'}; } else { print 'no got temp'; } } " 'BCInletTemperature = 90[C]' -> temp '90' 'BCInletTemperature = 33.56[C]' -> temp '33.56' 'Whatever = -.012[C]' -> temp '-.012' 'Wrong = 90 [C]' -> no got temp 'AlsoWrong = 9.0.1[C]' -> no got temp
Note that the regex might easily be extended to validate the entire record.


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^2: how to split a string at [ ?
by blaui (Initiate) on Jul 06, 2018 at 12:22 UTC
    Hello!

    Thanxs all a lot for the many suggestions. Because it seems the more felxible, I started to try with the above Regexp::Common.


    I modified it a littel bit.
    $tmp[5] = "BCInletTemperature = 90[C]"; print "$tmp[5] xx\n"; $temp = $tmp[5] =~ m{ = \s+ ($RE{num}{real}) \[ }xms; print "xxx $temp xxx\n";
    But running it gives:
    Name "charnames::CARP_NOT" used only once: possible typo at /usr/lib/p +erl5/5.18.2/Carp.pm line 437. Name "Regexp::Common::delimited::CARP_NOT" used only once: possible ty +po at /usr/lib/perl5/5.18.2/Carp.pm line 437. BCInletTemperature = 90[C] xx xxx 1 xxx
    Perl is
    perl --version This is perl 5, version 18, subversion 2 (v5.18.2) built for x86_64-li +nux-thread-multi
    at openSUse Leap 42.3.
    Do I need a newer version?

    Regards, buchi

      Do I need a newer version?

      No, but you do need to remember to put the brackets around $temp when you assign to it in order to ensure list context. You should also provide an SSCCE rather than 4 lines out of context as something could be wrong in the code you aren't showing too.

      Name "charnames::CARP_NOT" used only once: possible typo at /usr/lib/p +erl5/5.18.2/Carp.pm line 437. Name "Regexp::Common::delimited::CARP_NOT" used only once: possible ty +po at /usr/lib/perl5/5.18.2/Carp.pm line 437.

      Those are warnings, not errors, and I can't seem to be able to reproduce them here (don't have 5.18.2 handy though). Are you perhaps using perl -w on the command line or on the shebang line? In that case, see What's wrong with -w and $^W and use warnings; instead.

      The other issue with that code is that $string=~/(regex)/ won't return the match(es) unless you use it in list context, but my $temp = ... puts it in scalar context. To put the right-hand side into list context, use my ($temp) = $string =~ /(regex)/;.