[erlang-questions] Ternary Like Operation Idiom in Erlang

Robert Virding rvirding@REDACTED
Fri Dec 4 00:05:31 CET 2009


2009/12/3 Jarrod Roberson <jarrod@REDACTED>

> On Thu, Dec 3, 2009 at 4:08 AM, Michael Turner <leap@REDACTED> wrote:
> >
> >>Thanks to Dale's version I came up with this.
> >>
> >>F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true};
> >>[K,V] -> {K,V} end end.
> >
> > Cute, but with whitespace trailing after the "=", you get {key, " "},
> > which might not be the desired behavior.  Moreover, an embedded "=" in
> > the Value part (e.g, key='a=1' or something ridiculous like that) will
> > cause it to fail, which also might not be desired behavior.  Getting
> > close, though.
> >
> > The following
> >
> > Fm = fun(T) ->
> >   case re:split(string:strip(T),"=",[{return,list}]) of
> >    [K] -> {K, true};
> >    [K | V] -> {K, string:join (V, "=")}
> >   end
> > end.
> >
> > seems to cover those cases.  I'm assuming you don't care that there's
> > no whitespace stripped from the left end of the V string.  But maybe you
> > do.
>
> "key= " is valid and should parse to {"key"," "}, the spec for what is
> valid in my case is pretty strict.
> there should only be one "=" and anything else should FAIL. I will
> probably have to add some thing to catch
> those cases but for now I just want to get it to work with valid data.
>

In that case the easiest would be a small modification to Michael's code
(your func name):

fix(T) ->
    case re:split(T, "=", [{return,list}]) of
        [Key] -> {Key,"true"};                  %key
        [Key,[]] -> {Key,""};                      %key=
        [Key,Val] -> {Key,Val}                  %key=value
    end.

which will generate an error if you have more than one "=".

Robert


More information about the erlang-questions mailing list