[Gambas-user] print does not output if the var is FALSE, how to override?

Tobias Boege taboege at gmail.com
Fri Jun 29 20:30:02 CEST 2018


On Fri, 29 Jun 2018, PICCORO McKAY Lenz wrote:
> 2018-06-29 13:21 GMT-04:00 Tobias Boege <taboege at gmail.com>:
> 
> > No, it's not normal, as I said two mails ago. It should print "False"
> > as a string.
> >
> in my main function i return as Variant.. that's may be the problem..
> 
> ok how can i force the type of result from variant to boolean
> 

This is not the problem. Despite being inside a Variant "container",
False is still known to be a Boolean internally and will be printed
correctly. Just try it:

  Dim a As Variant = False
  Print a
  > False

> my function :
> 
> Public Function email(texto As Variant) As Variant
> 
>     Dim regex As New RegExp
>     Dim strPattern As String = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,8}$"
> 
>     If regex.Match(texto, strPattern, regex.Caseless) = True Then
>             Return texto
>     Endif
> 
>     Return False
> 
> End
> 
> when i used as:
> 
>     Print exu.email("mpes") & " y este " & exu.email("email at mail.com")
> 
> does not print "False" due the "Variant" implication i guess, so how can i
> emulated the php behaviour?
> 

Here, you are concatenating a Boolean to a string. This coerces the Boolean
to a string, but it does so using CStr(), which prints False as Null, which
is the empty string, as I explained earlier. It's not that you "Print", but
that you "&". Either use Str$(exu.email(...)) or

  Print exu.email("mpes");; "y este";; exu.email("email at mail.com")

and Print will take care of the human-friendly Boolean conversion.

BTW, I personally wouldn't write the function like that in the first place.
You only get in trouble because the returned datatype depends on the argument.
I would write it like this:

  Public Function email(texto As Variant) As Boolean
    ' For performance: compile the pattern once and cache it
    Return texto Match "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,8}$"
  Endif

and use it to actually branch in the code that wants to do something
with texto. But if you really value the one-liner here, there's probably
no other choice.

Regards,
Tobi

PS: As always when someone posts a regex for email addresses, yours is
not quite perfect. For starters, we have very long TLDs these days,
like .christmas, .engineering or .cancerresearch [1], which your regex
will reject.

[1] https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list