http://www.perlmonks.org?node_id=1052645


in reply to End of String in qr// expression

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>;

Replies are listed 'Best First'.
Re^2: End of String in qr// expression
by MidLifeXis (Monsignor) on Sep 06, 2013 at 13:03 UTC

    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

Re^2: End of String in qr// expression
by afoken (Chancellor) on Sep 06, 2013 at 19:28 UTC
    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". ;-)