Perl : 대체 문자열 변수에 역 참조 사용
Aug 21 2020
Perl에서 문자열 대체를 수행하고 있지만 패턴과 대체 문자열을 정규식 연산자 외부에 스칼라 변수로 저장했습니다. 문제는 대체 문자열이 역 참조를 사용할 수 있기를 원한다는 것입니다.
아래 코드가 문제를 더 명확하게 설명하기를 바랍니다.
my $pattern = 'I have a pet (\w+).'; my $replacement = 'My pet $1 is a good boy.'; my $original_string = 'I have a pet dog.';
# Not Working
my $new_string = $original_string =~ s/$pattern/$replacement/r;
# Working
#my $new_string = $original_string =~ s/$pattern/My pet $1 is a good boy./r;
# Expected: "My pet dog is a good boy."
# Actual: "My pet $1 is a good boy." print "$new_string\n";
답변
5 ikegami Aug 21 2020 at 12:23
s/$pattern/My pet $1 is a good boy./
약자
s/$pattern/ "My pet $1 is a good boy." /e
대체 표현식 ( "My pet $1 is a good boy."
)은 보간하는 문자열 리터럴입니다 $1
.
이것은
s/$pattern/$replacement/
약자
s/$pattern/ "$replacement" /e
대체 표현식 ( "$replacement"
)은 보간하는 문자열 리터럴입니다 $replacement
(아님 $1
).
방해가 될 수 있지만 perl
변수의 내용을 Perl 코드로 실행하는 습관이없는 것은 좋은 일입니다 . :)
gsub_copy
from String :: Substitution 을 사용 하여 문제를 해결할 수 있습니다.
use String::Subtitution qw( gsub_copy );
my $pattern = 'I have a pet (\w+)\.';
my $replacement = 'My pet $1 is a good boy.';
my $original_string = 'I have a pet dog.'; my $new_string = gsub_copy($original_string, $pattern, $replacement);
4 zdim Aug 21 2020 at 09:54
즉, $1
대체 문자열에서 단지 연속 문자입니다 $
및 1
및로를 만들기 위해 변수 나쁜 농구를 통해 이동해야 할 것 첫 번째 캡처. †
대안은 어떻습니까
my string = q(a pet dog);
my $pattern = qr/a pet (\w+)/; my $new = $string =~ s/$pattern/ repl($1) /er; sub repl { my ($capture) = @_;
return "$capture is a good boy";
}
서브가 정말 그냥
sub repl { "$_[0] is a good boy" }
조금 더 많지만 더 유능하고 유연합니다.
† 또는 ikegami의 답변에 따라 밝혀진대로 String :: Substitution 을 사용 하여 관련된 모든 '멋진'을 단일 호출로 래핑합니다.