gg48gg has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I seek your wisdom on matching an end of string/line using the qr quote like operator. I am simply trying to match a string of 8 characters, no more no less. This is not working as expected

here is my code

#!/bin/perl -w use strict; my $re = qr/\S{8}$/; my $input=""; until ($input=~m/$re/) { $input=<STDIN>; chomp $input; }

execution...

#./retest 1234 12345678 #./retest 123456789 #

Replies are listed 'Best First'.
Re: End of String in qr// expression
by choroba (Cardinal) on Sep 05, 2013 at 21:46 UTC
    To match "no more", you have to add the beginning anchor as well:
    my $re = qr/^\S{8}$/;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thanks. Now I'm embarrassed I didn't see that. It was matching the end of string. Doh!
Re: End of String in qr// expression
by wanna_code_perl (Friar) on Sep 06, 2013 at 01:57 UTC

    choroba was right on about the ^ anchor. However, if you really just want to match any string exactly 8 characters long, why not use length?

    my $LEN = 8; # Desired length my $match; while ($match = <STDIN>) { chomp $match; last if $LEN == length($match); } die "Didn't find a match" if not defined $input; print "First match: '$match'\n";

    More Less generally, you might use List::MoreUtils::firstval():

    Update: as MidLifeXis points out, using firstval will require Perl to slurp in STDIN. This will be slower on files many megabytes large, or slow streams via pipelining. It will also never finish if STDIN never sees an EOF (again via pipelining). These may not be applicable to your situation, but choose carefully.

    use List::MoreUtils 'firstval'; my $match = firstval { chomp; $LEN == length } <STDIN>;

    The $LEN == length check could be replaced with anything you like. You can even pass in a code reference instead of the direct block, as in my $match = firstval \&my_match_sub, <STDIN>;

      I don't believe that <STDIN> behaves like a lazy list. STDIN would need to eof before firstval would even get a look at the data. At least under 5.8.9. This behaves differently than the while ($x = <STDIN>) { ... } block.

      --MidLifeXis

      if you really just want to match any string exactly 8 characters long, why not use length?

      Note hat /^\S{8}$/ does not match ANY 8 characters, but only 8 non-whitespace characters. length($input)==8 accepts any 8 characters.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)