How to get a regex to start from the beginning of a string

后端 未结 4 1011
心在旅途
心在旅途 2021-01-13 19:01

This is an oddball issue I\'ve encountered (and probably have seen before but never paid attention to).

Here\'s the gist of the code:

my $url = \'htt         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-13 19:34

    The /g modifier, in scalar context, doesn't do what you think it does. Get rid of it.

    As perlretut explains, /g in scalar context cycles over each match in turn. It's designed for use in a loop, like so:

    while ($str =~ /pattern/g) {
        # match on each occurence of 'pattern' in $str in turn
    }
    

    The other way to use /g is in list context:

    my @results = $str =~ /pattern/g; # collect each occurence of 'pattern' within $str into @results
    

    If you're using /g in scalar context and you're not iterating over it, you're almost certainly not using it right.

提交回复
热议问题