Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Perl 6 (examples of Arrays ,Hash and functions)

by mkirank (Chaplain)
on May 13, 2005 at 12:41 UTC ( #456696=perlmeditation: print w/ replies, xml ) Need Help??

These examples were taken from the Pugs (t and examples ) directories and I thought It would be useful as a quick reference guide . These examples are not exhaustive or complete but should help as a reference

Arrays

#!/usr/bin/pugs use v6; my @array = (); say @array.end; # prints -1 (empty array) @array = (1..43); # array from 1 to 42 . say " now array size is " ~ @array.end; my $get_last_element = pop @array; say "removed last element $get_last_element "; say " now array size is " ~ @array.end; say "getting first element " ~ shift @array; say " now array size is " ~ @array.end; unshift @array, 'foo';#adding first element say @array[0]; push @array, 'bar';#adding bar to last element say @array[@array.end]; my @arr = <1 2 3 4>; # say "another way of getting the size " ~ +@arr;#getting the si +ze splice @arr; say " size after splice " ~ +@arr;#getting the size my @a = <red, green, blue>; say " splice() in scalar context returns last element of array + " ~ splice(@a, 1, 2); @a = (2..10); splice(@a,0,0,0,1);## adding 0 an 1 to the beginning splice(@a,5,1,'x');## Replacing the 5th element with x say @a; splice(@a, @a, 0, 12, 13);##append 12 and 13 to the array say @a; say @a.exists(0); ## exists(positive index) on arrays (0) say @a.keys;# without spaces say ~@a.keys; # print with spaces ~ say ~@a.values; @array = <a b c d>; my @kv = @array.kv; say @kv;# prints 0a1b2c3d @array = <d c b a>; say @array.sort;# prints abcd @array = <a b c d>; my @pairs = @array.pairs; say @pairs;#prints 0 a1 b2 c3 d say @pairs[0].key;# print 0 say @pairs[0].value;# print a @array.delete(2);#deletes c @array = <a b c d>; @array.delete(0, 3);# deletes 'a' and 'd' say @array; @array = <a b c d>; @array.delete(-2);#deletes c say @array; @array = <a b c d e f>; @array.delete(2, -3, -1);# deletes "c d f" say @array; ## Grep my @list = (1 .. 10); my @result = grep { ($_ % 2) }, @list;## grep say @result;# prints 1 3 5 7 9 @result = @list.grep():{ ($_ % 2) };## another way to do it ## Map @result = map { $_ * 2 } @list; @result = @list.map():{ $_ * 2 };## another way to do it say @result;# @array = <a b b c d e b b b b f b>; # @array.uniq @array.max @array.min; to do in pugs


Hashes


#!/usr/bin/pugs use v6; my %hash = (a => 1, b => 2, c => 3, d => 4); say %hash;# prints a 1b 2c 3d 4 say ~%hash.keys.sort;#print a b c d say sort(keys(%hash)); #p5 style say ~%hash.values.sort;#print 1 2 3 4 say sort(values(%hash)); #p5 style say "num of elements in hash is " ~ +%hash;# prints 4 say %hash.pick.key;# pick any key say %hash.pick.value;#pick any value # print all key and value for (%hash.kv) -> ($key,$value) { say "hash key is $key val is $value "; } my @pairs; @pairs = %hash.pairs.sort; say @pairs;#prints a 1b 2c 3d 4 say @pairs[2].key;# prints c say @pairs[2].value;# prints 3 %hash.delete("a");# delete key a say %hash.exists("b");#prints 1 %hash.exists("x");


Functions


#!/usr/bin/pugs use v6; ############################################################ ###Perl5ish subroutine declarations#### tmp(3,'asd',4); moditest(100); sub tmp { say ~@_; } ## @_ is rw to do in pugs sub moditest (*@_ is rw) { say "val is @_[0]"; #@_[0] = 99 ; #say "modified val is @_[0]"; } ############################################################ ### Multi Sub### foo ('string_passed'); foo (4); foo($*ERR); # type based dispatching multi sub foo (Int $bar) { say "Int " ~ $bar } multi sub foo (Str $bar) { say "Str " ~ $bar } multi sub foo (IO $fh) {say "IO" } ############################################################ ###Pointy Sub### my ($sub, $got); $got = ''; $sub = -> $x { $got = "x $x" }; say $sub.(123); $sub = -> ($x) { $got = "x $x" }.(456).say; my $str = ''; ### Output of the below ##start outer ## before ## pointy still sees outer's &outer ##calling outerinner ret ##str is inner ## End Output say " calling outer" ~ outer(); say "str is " ~ $str; sub outer { say "start outer"; my $s = -> $x { say " pointy still sees outer\'s $?SUBNAME"; $str ~= 'inner'; return 'inner ret'; }; say " before "; $s.(); $str ~= 'outer'; say " In Outer $?SUBNAME"; return 'outer ret'; } ############################################################ ###Optional Parameters ### ## Optional positional parameters are specified after all the ## required parameters and each is marked with a ? before the paramete +r my_substr('Kiran'); my_substr("foobar",len=>3); sub my_substr ($str, ?$from = 100, ?$len = Inf) { say "str is $str from is $from len is $len"; } say "calling " ~ xml_tag('sometag'); sub xml_tag ($tag, ?$endtag = matching_tag($tag) ) { say "tag is $tag endtag is $endtag"; } sub matching_tag ($tmp) { return "GOtta $tmp"; } ############################################################ ###Named Parameters ### #Named parameters follow any required or optional parameters in the si +gnature. # They are marked by a + before the parameter. my ($text,$case,$justify) = formalize('title', case=>'upper'); say "text is $text case is $case justify is $justify "; ($text,$case,$justify) = formalize('head', justify=>'right',case=>'lo +wer'); say "text is $text case is $case justify is $justify "; ($text,$case,$justify) = formalize('head', :justify<middle>,:case<any +case>);# another way say "text is $text case is $case justify is $justify "; sub formalize($text, +$case, +$justify) returns List { return($text,$case,$justify); } ############################################################ ###Slurrrp ### #Slurpy parameters follow any required or optional parameters. #They are marked by a * before the parameter: my @arr = 1..3; # array stores three scalars #bar(@arr); # error: only one arg bar(@arr); # ok sub bar(*$x, *$y, *$z) { say "x $x"; say "y $y "; say "z $z"; }


Update: added links as per dragonchild suggestion

Comment on Perl 6 (examples of Arrays ,Hash and functions)
Select or Download Code
Re: Perl 6 (examples of Arrays ,Hash and functions)
by dragonchild (Archbishop) on May 13, 2005 at 13:01 UTC
    These examples were taken from the Pugs (t and examples) directories . . .

    Why wouldn't links to the SVN repository be more appropriate, seeing as the examples are going to change, but your node won't keep pace?


    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
Re: Perl 6 (examples of Arrays ,Hash and functions)
by fireartist (Chaplain) on May 13, 2005 at 14:38 UTC

    When I think "quick reference guide", I think of something that can be printed on A4, and easily grokked when it's stuck to the board above my desk. Whereas this is really hard to make anything of.

Re: Perl 6 (examples of Arrays ,Hash and functions)
by revdiablo (Prior) on May 13, 2005 at 16:06 UTC

    I'm glad to see more people trying Perl 6 via Pugs! I think the more advocacy and discussion we can generate -- such as Limbic~Region has been doing -- the better it'll be. That being said, I have a comment about your specific post:

    This would probably be more useful if it had equivalent Perl 5 code to compare to. A table with two columns would work very nicely, except some of these snippets are a bit long for that. Perhaps that should be a clue to shorten the long snippets, to reduce them to bite-sized chunks.

Re: Perl 6 (examples of Arrays ,Hash and functions)
by Cap'n Steve (Friar) on May 16, 2005 at 06:01 UTC
    As someone who's never taken a look at Perl 6 before, I have to say that's pretty cool, although more than a little scary.

    I agree that it could use some formatting, though. That's a pretty big chunk of code.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://456696]
Approved by audreyt
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2014-09-21 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (166 votes), past polls