Sample code for 30+ languages & platforms
Perl Requires Chilkat v11.4.0+

Call a JavaScript Function Returning a Boolean

See more JavaScript Examples

Demonstrates how to call a JavaScript function that returns a boolean.

Chilkat Perl Downloads

Chilkat2 Perl
use strict;
use warnings;
use Chilkat2;

# This is the JavaScript function we'll call:

# function isEven(number) {
#     return number % 2 === 0;
# }

my $sbScript = Chilkat2::StringBuilder->new;
$sbScript->Append('function isEven(number) { return number % 2 === 0; }');

my $js = Chilkat2::Js->new;

my $result = Chilkat2::JsonObject->new;
$result->EmitCompact(0);

# Call Eval to add the function to the context's global object
my $success = $js->Eval($sbScript, $result);
if (!$success) {
    # Examine the result for an exception.
    print $result->Emit(), "\n";

    # Also examine the LastErrorText.
    print $js->LastErrorText, "\n";
    exit;
}

# ------------------------------------------------------------------------------
# Call the function isEven(8)

my $funcCall = Chilkat2::JsonObject->new;

# Create JSON specifying the function name and arguments

# {
#   "name": "isEven",
#   "args": [ 8 ]
# }

$funcCall->UpdateString('name', 'isEven');
$funcCall->UpdateInt('args[0]', 8);

$success = $js->CallFunction($funcCall, $result);
if (!$success) {
    # Examine the result for an exception.
    print $result->Emit(), "\n";

    # Also examine the LastErrorText.
    print $js->LastErrorText, "\n";
    exit;
}

print $result->Emit(), "\n";

# Output:
# {
#   "type": "bool",
#   "value": true
# }

my $retval = $result->BoolOf('value');
print(($retval ? 1 : 0), "\n");

# Output:
# 1