in reply to Golf: string complement

39 strokes

sub invert{ #23456789012345678901234567890123456789 $_=pack'C*',1..255;eval"tr/$_[0]//d";$_ } print invert('just Another Edge Case Waiting to Crash!');

Update

Updated invert text as per below :-)

cheers

tachyon

Replies are listed 'Best First'.
Re: Re: Golf: string complement
by japhy (Canon) on May 15, 2004 at 04:47 UTC
    You need to wrap $_[0] in \Q...\E, because if it contains a hyphen or a forward-slash, you'll get unexpected results.
    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      You gotta hate those edge cases! Having just had a look at your example you are passing an array not a string so it looks like a different problem.

      38 strokes with fix in 35 strokes.

      sub invert{ #2345678901234567890123456789012345678 $_=pack'C*',1..255;s/[\Q$_[0]\E]//g,$_ } print invert('/just Another Bug to Fix!/'); # 35 strokes using @_ hack sub invert{ #2345678901234567890123456789012345 $_=pack'C*',1..255;s/[\Q@_\E]//g,$_ } print invert('/just Another Bug to Fix!/');

      cheers

      tachyon

        I'm passing an array? I'm using $_[0] which is where the argument to the function is, and I'm iterating over the list 1..255, but I'm not receiving or returning an array from the function. And I am using \Q in the regex.
        _____________________________________________________
        Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
        @_ hack?

        I suppose, though it's expected behavior. Within the RE @_ is interpolated just like "@array\n" would be. Since @_ should only have one argument, there will be only one element in the list. Thus, there is no extra space character interpolated. If @_ contained more than one element, that would result in a space character being placed in the character class, which would cause the space character to be absent from the inverted string even if the original string never had a space in it. ...so it's easy to break this solution, but assuming the sub is called as intended, it will only have one arg, and the point will be moot.

        I guess it is a hack. ;)


        Dave