1. Shlomi Fish
  2. Perl-XS-Guide

Commits

shl...@cec68495-dca5-4e2b-845c-11fdaaa4f967  committed 06e5be7

Added the lookup_mystring_in_hash.

  • Participants
  • Parent commits bcabdbf
  • Branches default

Comments (0)

Files changed (4)

File perl5/ext-embed-internals/docbook/examples/incremental-examples-1/XSTest/MANIFEST

View file
 t/07-assign-string-to-ref.t
 t/09-assign-to-array.t
 t/10-array-from-scratch.t
+t/11-lookup-hash-constant.t
 t/boilerplate.t
 t/lib/scripts/get-24-leak-test.pl
 t/lib/scripts/get-string-leak-test.pl

File perl5/ext-embed-internals/docbook/examples/incremental-examples-1/XSTest/lib/XSTest.pm

View file
 This function is meant to demonstrate creating new array references and 
 populating them.
 
+=head2 $value = lookup_mystring_in_hash(\%hash)
+
+Equivalent to C<< $value = $hash{'mystring'} >>
+
+This function is meant to demonstrate hash lookup. Returns undef if the
+hash does not contain the key C<'mystring'> .
+
 =head1 AUTHOR
 
 Shlomi Fish, C<< <shlomif@iglu.org.il> >>
 Copyright 2007 Shlomi Fish, All Rights Reserved.
 
 This program is free software; you can redistribute it and/or modify it
-under the same terms as Perl itself.
+under the terms of the MIT/X11 License.
 
 =cut
 

File perl5/ext-embed-internals/docbook/examples/incremental-examples-1/XSTest/lib/XSTest.xs

View file
     OUTPUT:
         RETVAL
 
+SV *
+lookup_mystring_in_hash(HV * hash)
+    PREINIT:
+        SV **value;
+    CODE:
+        /* hv_fetch() takes the hash, the string, the string length,
+         * and whether it is an lvalue or not. */
+        if ((value = hv_fetch(hash, "mystring", 8, FALSE)))
+        {
+            RETVAL = newSVsv(*value);
+        }
+        else
+        {
+            RETVAL = &PL_sv_undef;
+        }
+    OUTPUT:
+        RETVAL
+

File perl5/ext-embed-internals/docbook/examples/incremental-examples-1/XSTest/t/11-lookup-hash-constant.t

View file
+use strict;
+use warnings;
+
+use Test::More tests => 3;
+
+use XSTest;
+
+{
+    my $value = XSTest::lookup_mystring_in_hash({ 'mystring' => "Hello" });
+
+    # TEST
+    is ($value, "Hello", "Lookup is OK.")
+}
+
+{
+    my $value = XSTest::lookup_mystring_in_hash(
+        { 'mystring' => "Hello", 'author' => "Jane", }
+    );
+
+    # TEST
+    is ($value, "Hello", "Lookup is OK with other value.")
+}
+
+
+{
+    my $value = XSTest::lookup_mystring_in_hash(
+        { 'author' => "Jane", year => 1950, }
+    );
+
+    # TEST
+    ok (!defined($value), "Return undef if value not found.")
+}
+