#!/usr/bin/ruby

# Example on how to create and use a GDBM database.

require('GDBM_File')

var h      = Hash()
var file   = File("fruit") -> unlink
var db_obj = Perl.tie(h, "GDBM_File", file, %S<GDBM_File>.GDBM_WRCREAT, 0666) || die "Error: #{%perl<$GDBM_File::gdbm_errno>}"

assert_eq(%perl<$GDBM_File::gdbm_errno>, "No error")

say db_obj

# Add a few key/value pairs to the file
h{"apple"}  = "red"
h{"orange"} = "orange"
h{"banana"} = "yellow"
h{"tomato"} = "red"

# Check for existence of a key
print "Banana Exists\n\n" if h.exists("banana")

assert_eq(Str(h{:banana}), "yellow")

# Delete a key/value pair.
h.delete("apple")

# print the contents of the file
h.each_kv {|k,v|
    say [k,v]
}

db_obj.close
assert_eq(Perl.untie(h), 1)

Perl.tie(var h2 = Hash(), "GDBM_File", file, %S<GDBM_File>.GDBM_READER, 0666) || die "Error: #{%perl<$GDBM_File::gdbm_errno>}"

assert_eq(Str(h2{:banana}), 'yellow')

assert_eq(
    h2,
    Hash(
        "banana" => *'yellow',
        "orange" => *'orange',
        "tomato" => *'red',
    )
)

say file.size
Perl.untie(h2)
file.unlink
