제가 쓰고있는 게임에서 두 개의 이름을 잘못 입력 한 이상한 경우가있었습니다. 그들은 서로를 미러링합니다. 예를 들어 헨리 패트릭과 패트릭 헨리가 있는데, 제가 작성한 코드를 실수로 바꾸고 싶었습니다.
이제 아래의 PERL 코드는 그렇게하지만 임시 교체 문자열 heinous-hack-string
은 해킹입니다. 일을하는 더 우아한 방법이 있습니까?
##################
#nameflip.pl
#
# this flips names where I mistakenly switched first-last and last-first
#
use strict;
use warnings;
my $mystr = "There's this guy named Henry Patrick, and there's another guy named Patrick Henry, " .
"and I confused them and need to switch them now!";
print "Before: $mystr\n";
print "After: " . stringNameSwitch($mystr, "Patrick", "Henry") . "\n";
##############################
# awful hack of a subroutine.
#
# what regex would do better?
#
# right now I just want to switch (name1 name2) <=> (name2 name1)
sub stringNameSwitch
{
my $temp = $_[0];
$temp =~ s/$_[1] +$_[2]/heinous-hack-string/i;
$temp =~ s/$_[2] +$_[1]/$_[1] $_[2]/i;
$temp =~ s/heinous-hack-string/$_[2] $_[1]/i;
return $temp;
}
이렇게, 아마도? 지점 리셋 구조는 (?|...)
두 개의 이름으로 캡처 할 수 $1
와 $2
관계없이 외관의 순서의.
use strict;
use warnings 'all';
my $mystr = <<END;
There's this guy named Henry Patrick,
and there's another guy named Patrick Henry,
and I confused them and need to switch them now!
END
print name_switch($mystr, qw/ Henry Patrick /);
sub name_switch {
my ($s, $n1, $n2) = @_;
$s =~ s/\b(?|($n1)\s+($n2)|($n2)\s+($n1))\b/$2 $1/gr;
}
There's this guy named Patrick Henry,
and there's another guy named Henry Patrick,
and I confused them and need to switch them now!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다