Skip to content

Commit

Permalink
add hello_to_persons_arrayref(AV* persons) function
Browse files Browse the repository at this point in the history
...which demonstrates:

 - iterate over elements of an array reference
 - check for contained element types
 - cast according to element type
  • Loading branch information
renormalist committed Jun 20, 2012
1 parent 37739bb commit 2d1dcc6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Diaries.xs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,31 @@ is_even(input)
RETVAL = (input % 2 == 0);
OUTPUT:
RETVAL

void
hello_to_persons_arrayref(persons)
AV *persons;
PREINIT:
I32 i;
I32 len;
SV** element;
STRLEN str_len;
char * el_str;
I32 el_int;
PPCODE:
len = av_len(persons);
printf("Hello, %d persons:\n", len+1);
for (i = 0; i <= len; i++) {
element = av_fetch(persons, i, 0);
if (element != NULL) {
if (SvPOK(*element)) {
el_str = SvPV(*element, str_len);
printf(" %d: Hello, %s!\n", i, el_str);
} else if (SvIOK(*element)) {
el_int = SvIV(*element);
printf(" %d: Hello, %d!\n", i, el_int);
} else {
printf(" %d: (ignored)\n", i);
}
}
}
2 changes: 2 additions & 0 deletions lib/Acme/The/Secret/XS/Diaries.pm
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ use Sub::Exporter
exports => [
qw( hello
hello_to
hello_to_persons_arrayref
is_even
),
],
groups => {
all => [ qw(hello
hello_to
hello_to_persons_arrayref
is_even
) ],
},
Expand Down
9 changes: 9 additions & 0 deletions t/diaries.t
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ is(is_even(0), 1, "0 -> even");
is(is_even(1), 0, "1 -> uneven");
is(is_even(2), 1, "2 -> even");
hello_to("birne");
my $hashref = {
Mom => "Dear",
Holle => "Frau",
1234567 => "lucky number",
3456 => 12,
President => "Mr.",
};
my $arrayref = [keys %$hashref];
hello_to_persons_arrayref($arrayref);

ok(1);
done_testing;

0 comments on commit 2d1dcc6

Please sign in to comment.