Re: File::Copy ??

2017-03-22 Thread Brad Gilbert
For basic copy and move, the built-in subs should work

https://docs.perl6.org/routine/copy
https://docs.perl6.org/routine/move

On Wed, Mar 22, 2017 at 12:24 AM, ToddAndMargo  wrote:
> Hi All,
>
> Do we have anything like
>
> http://perldoc.perl.org/File/Copy.html
>
> under another name?
>
> Nothing showed up in
>https://modules.perl6.org/#q=file%3A%3A
>
>
> Many thanks,
> -T
>
>
> --
> 
> Yesterday it worked.
> Today it is not working.
> Windows is like that.
> 


Re: Am I suppose to be able to change a variable's type on the fly?

2017-03-22 Thread Brad Gilbert
The default type constraint is Mu, with a default of Any (everything
is of type Mu, and most are of type Any)

You shouldn't be able to change the type constraint of a scalar
container (used for rw variables)

Changing the type of a value, of course makes no sense. (a Str is
always a Str, even when you use it as a number)

Basically no you can't change the type, but you didn't do that anyway.

On Wed, Mar 22, 2017 at 12:59 AM, ToddAndMargo  wrote:
> Hi All,
>
> Yes, I know, Perl is "lexiconical".
>
> $ perl6 -e 'my $x="abc"; $x=1E23; print "$x\n";'
> 1e+23
>
> $ perl6 -e 'my Str $x="abc"; $x=1E23; print "$x\n";'
> Type check failed in assignment to $x; expected Str
> but got Num (1e+23) in block  at -e line 1
>
> So, unless I specifically declare a variable as a
> particular type, I can change its "type" on the fly.
> Is that correct?
>
>
> Many thanks,
> -T
>
>
> --
> ~~~
> Serious error.
> All shortcuts have disappeared.
> Screen. Mind. Both are blank.
> ~~~


Re: next

2017-06-19 Thread Brad Gilbert
On Mon, Jun 19, 2017 at 11:15 AM, Andy Bach  wrote:
>
> On Fri, Jun 16, 2017 at 11:11 PM, Gabor Szabo  wrote:
>>
>> If the loop has some action and a condition it will jump to  execute
>> the action again (increment $i) and check the condition and act
>> accordingly doing the next iteration or quitting the loop.
>
>
> Just checking but there are no "continue" blocks for loop control stmts
> anymore, P6? Google suggested maybe foreach loops but that was back in 2011.
>

Instead of a `continue` block after the loop, there is a `NEXT` phaser
inside the block

for 1..4 {
  next if $_ == 3;
  .^name.say;

  NEXT .say;
}

Which results in:

Int
1
Int
2
3
Int
4


Re: need help with "next"

2017-05-23 Thread Brad Gilbert
You do realize that `next` immediately stops the current iteration and
goes onto the *next* one right?
That is, there is no point putting any code after it because it will
never be run.

On Tue, May 23, 2017 at 11:30 PM, ToddAndMargo  wrote:
> Hi All,
>
> I have a test code in progress and I haven't figured out
> how to get 'next' to work the way I want.
>
> next if $Line.contains( "TASK type" );
>
> works, but
>
> if $Line.contains( "TASK type" ) {
>next;
>
> does not.
>
> What am I missing?
>
> Many thanks,
> -T
> yes I know I still have some things to fix on it.
>
>
> 
> #!/usr/bin/env perl6
>
> use strict;
>
> my @Data = 'Mission D',
>'   Sol Wheat',
>'   Ted Moon',
>'';
> # for @Data -> $Line { say "$Line"; }
>
> for @Data -> $Line {
># next if $Line.contains( "TASK type" );
>if $Line.contains( "TASK type" ) {
>   next;
>   my $Name = $Line;
>   if $Name.contains( "NAME type" ) {
>  $Name ~~ s/.*?\>//;
>  $Name ~~ s/\<.*//;
>  say $Name;
>   }
>}
> }
>
> 
>
>
> --
> ~~
> Computers are like air conditioners.
> They malfunction when you open windows
> ~~


Re: How do you call the variable types?

2017-06-09 Thread Brad Gilbert
@ does the Positional role
% does Associative
& does Callable
$ causes its value to be an item (its values do not flatten into an
outer list when you use `flat`)

my %hash is SetHash;

Array does Positional, and all of its values are itemized

We are unlikely to call $ variables "generic" because the word
"generic" is too generic.
For example Java has generics, and they are not variables.
Why muddy the waters by using a word that has many different meanings
in different programming languages?

On Fri, Jun 9, 2017 at 1:21 AM, Richard Hainsworth
 wrote:
> It also seems to me that 'scalar' gives the wrong impression compared to
> arrays. A scalar in a vector is a component of a vector.
>
> I was thinking of "generic".
>
> Hence "$variable" is a generic variable because it can hold any type of
> content.
>
>
>
> On Friday, June 09, 2017 02:10 PM, Gabor Szabo wrote:
>>
>> Looking at https://docs.perl6.org/language/variables there are 4
>> variable types with sigil:  $, @, %, &.
>> In Perl 5 I used to call them scalar, array, hash, and function
>> respectively, even if the scalar variable had a reference to an array
>> in it.
>>
>> How do you call them in Perl 6?
>>
>> As I understand @ always holds an array (@.^name is always Array or
>> some Array[type]). Similarly % always holds a hash and & is always a
>> function or a method.
>> So calling them array, hash, and function sounds good.
>>
>> However I am not sure what to call the variables with a $ sigil?
>> Should they be called "scalars"? Wouldn't that case confusion as there
>> is also a container-type called Scalar.
>>
>> The word "scalar" appears twice in the document describing the
>> variables: https://docs.perl6.org/language/variables and a total of
>> 135 in the whole doc including the 5to6 documents and the document
>> describing the Scalar type.
>> The document describing the Scalar type:
>> https://docs.perl6.org/type/Scalar the term "$-sigiled variable" is
>> used which seems to be a bit long for general use.
>>
>> So I wonder how do *you* call them?
>>
>> Gabor


Re: <<>> question

2017-10-05 Thread Brad Gilbert
On Thu, Oct 5, 2017 at 11:44 AM, Andy Bach  wrote:
>
>> is
><<>>
>> synonymous with
>qw[]
> ?

`<<>>` is the same as `qqww<<>>`
Which is short for `Q :qq :ww <<>>`

the `:qq` is short for `:double`, that is it turns on double quote behaviour
`:double` is short for `:scalar :array :hash :function :closure :backslash`

the `:ww` is short for `:quotewords` which is similar to `:words` except
it allows quoting to override where it splits the strings.

`Q :quotewords < a 'b c' d >` turns into `( 'a', 'b c', 'd' )`

Note that if you explicitly use `q` `qq` or `Q` that the brackets will
not change how
the construct works. (So even if you use `Q<<…>>` it will be the same as `Q'…'`)


Re: tip: case insensitive test

2017-11-07 Thread Brad Gilbert
The way to add `:i` to regex without using `m` is to include it inside
of the regex `/:i abcdef/`

On Fri, Nov 3, 2017 at 5:30 PM, ToddAndMargo  wrote:
> Dear List,
>
> Okay, I am pretty sure there are no copyrights here.
>
> I had a problem where I had to read through a YUGE log file and
> pick out those entries with a particular name in it.  Problem"
> it was the same name but three different capitalizations and
> the the capitalization was a moving target.  I couldn't count
> on it staying the same.
>
> and `i/test/` or `:i/test/` did not work.
>
> One of the guys helped me out with this on the chat line.
> `m:i/test/` did the trick, and forgave me for not actually
> doing a match.  He said one of the benefits of "m" was that
> it allows for more things like "i" to be included
>
> Here is a test one liner:
>
> $ perl6 -e 'my $x="abcDEF"; if ( $x ~~ m:i/abcdef/ ) { say "yes";} else {
> say "no";}'
>
> yes
>
>
> -T
>
> --
> ~~~
> Having been erased,
> The document you're seeking
> Must now be retyped.
> ~~~


Re: any better explanation of look ahead assertions

2018-05-10 Thread Brad Gilbert
On Thu, May 10, 2018 at 9:09 PM, ToddAndMargo <toddandma...@zoho.com> wrote:
> On 05/10/2018 07:06 PM, Brad Gilbert wrote:
>>
>> You could read how they work in PCRE
>
>
> What is PCRE?

Perl Compatible Regular Expressions,

Basically someone reimplemented the regular expression engine found in Perl,
and that is the basis of what every other language uses.


Re: any better explanation of look ahead assertions

2018-05-10 Thread Brad Gilbert
On Thu, May 10, 2018 at 8:13 PM, ToddAndMargo  wrote:
> Hi All,
>
> Looking at:
> https://docs.perl6.org/language/regexes#Lookahead_Assertions
> https://docs.perl6.org/language/regexes#Lookbehind_assertions
>
> I can't tell heads from tails.  Does anyone know of a better
> reference/explanation for beginners?
>

You could read how they work in PCRE, as there are a lot more sources for it.

It is difficult to wrap your head around, as it matches some text without moving
the current position.

Also I find that I don't use it that often, so you might just want to
put off learning it
until you are more experienced using regexes. Who knows, maybe by then it will
be easier to understand.

I might look into making it easier to understand.
(I'm all talk though, so I wouldn't hold your breath)


Re: I need `dir` help

2018-05-10 Thread Brad Gilbert
On Thu, May 10, 2018 at 7:02 PM, ToddAndMargo  wrote:
> On 05/10/2018 04:56 PM, Brandon Allbery wrote:
>>
>> I think you'll need to provide a better explanation of what you're trying
>> to accomplish. I can think of lots of ways to do useful things with the
>> output of dir(), but have no idea which one(s) you need.
>
>
> I wanted to loop through entries as an exercise.  Although this
> is not really necessary with `indir` as you can ask directly
> if something is in a directory.
>

That's not what `indir` does

What it does is change the current working directory inside of a block

put $*CWD; # /home/brad
indir "/tmp", {
put "in directory $*CWD"; # /tmp
.put for dir()
}
put $*CWD; # /home/brad


Also this

$ perl6 -e 'for dir() -> $x { my $y="$x"; say $y };'

can be simplified to any of:

$ perl6 -e 'for dir() -> $x { say ~$x }'
$ perl6 -e 'for dir() -> $x { put $x }'
$ perl6 -e '.put for dir'


Re: mixin syntax: does vs but

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 2:16 PM, JJ Merelo  wrote:
> This is what the documentation says: https://docs.perl6.org/syntax/WHAT
> You can override it, but we'll pay no attention anyway, basically. So you
> can't achieve it otherwise, I guess.

It is easy to achieve.

sub user-made-what ( ::Type ) { Type }

say 42. # says (Int)

>
> El mar., 12 jun. 2018 a las 21:14, JJ Merelo ()
> escribió:
>>
>>
>>
>> El mar., 12 jun. 2018 a las 21:11, Brandon Allbery ()
>> escribió:
>>>
>>> I should clarify this, but I'm not recalling full details at the moment
>>> which is why I didn't originally.
>>>
>>> Perl uses a metaobject protocol (MOP, which you'll see in various places
>>> in the docs). The "macro" to access the metaobject is the .HOW
>>> pseudo-method. If you do this for a normal class or object of that class,
>>> you get Perl6::Metamodel::ClassHOW back. This is what the .^method syntax is
>>> accessing; it's short for (thing).HOW.method((thing), ...). The metaclass
>>> doesn't magically know its children, so the object has to be used once to
>>> get at its metaclass and a second time to tell the metaclass what it is to
>>> introspect.
>>>
>>> I'm not seeing documentation for what .WHAT actually does; it (correctly)
>>> notes that it's implemented specially within the compiler (hence "macro")
>>> but not how you achieve it otherwise. Then again, .HOW has the same issue;
>>> there's a bit of a bootstrapping issue with getting at the metamodel, you
>>> need to have it first. Which is why it's wired into the compiler and gets
>>> those uppercase pseudo-method names.
>>
>>
>> All the metamodel is not exactly part of the language; it's part of the
>> compiler. So it's in the gray NOT-SPECCED zone regarding documentation of
>> "Perl 6" the language, as oposed to "Perl 6, the implementation by Rakudo".
>> But it's a gray zone and sometimes you fall short of documenting things like
>> WHAT. I'll see what we can in that area.
>>
>> JJ
>>
>
>
> --
> JJ


Re: mixin syntax: does vs but

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 12:55 PM, Joseph Brenner  wrote:
> Thanks, both your suggestion and JJ Merelo's work, but I think I like
> yours for readability:
>
>   # # using binding, suggested by JJ Merelo 
>   # my @y := @x but LookInside;
>
>   # suggested by Elizabeth Mattijsen l...@dijkmat.nl
>   my @y does LookInside = @x;
>
> I actually found the use of "but" in the objects docs to be
> tremendously confusing at first:  it looks like some sort of
> conditional check, like "unless".

The reason `but` exists is basically for the following

my $v = 0 but True;

if $v { say $v } # prints 0

In Perl 5 it is common to return the string `"0 but true"` for a value that is
both 0 and true.

Since one of the design philosophies of Perl 6 is to reduce the number
of special cases this was made to be more generally useful.

Note that you should not do the following

my $v = 0;
$v does True;

say 'WTF!' if 0; # prints WTF!

Basically you can use `but` anywhere you like, but be careful with `does`.

> On Tue, Jun 12, 2018 at 1:01 AM, Elizabeth Mattijsen  wrote:
>>> On 12 Jun 2018, at 09:06, Joseph Brenner  wrote:
>>>
>>> I thought this would work to make a copy of @x but with the role
>>> "LookInside" attached to it:
>>>
>>>   my @y = @x but LookInside;
>>>
>>> But that didn't add the role to @y. E.g.

That is effectively the same as:

my @y = (@x but LookInside).map: *.self;

That is @ sigiled variables tend to slurp in iterable values.

>>>  say @y.^WHAT

If you want to print the name use `.^name`.

If you want the type object for more advanced usages use `.WHAT`.

>>>
>>> Would just report (Array), not (Array+{LookInside}).
>>
>> What you’re doing here, is assigning the elements of an Array but Lookinside 
>> to a normal Array.  The elements of the Array do not have any roles mixed 
>> in, so you wind up with a normal Array with normal elements in them.  
>> Perhaps you meant:
>>
>> my @y does LookInside = @x;
>>
>> Here you create an Array @y with the role LookInside mixed in, and *then* 
>> assign the values from @x.
>>


Re: stackoverflow vs the world (and perl6-users)

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 3:57 PM, Brandon Allbery  wrote:
> I replied to this one in private, but I want to make a point in public as
> well.
>
> On Tue, Jun 12, 2018 at 4:24 PM Brad Gilbert  wrote:
>>
>> The barrier is not with Stack Overflow. (←What I obviously meant)
>> The barrier is within you.
>
>
> There's an insidious assumption hidden in here: that "the barrier is within
> you" means it's a modifiable barrier. Or, for that matter, it should be.
>
> For some of us, it's not. I was not overstating earlier when I made a
> reference to the Nobel Prize.
> And there are also those for whom it's not as modifiable as this attitude
> assumes, or for whom modifying it is not the best of ideas.
>
> Think about this one a bit next time you want to tell someone it's "all in
> their head". Because it might just be literally true.
>

I absolutely knew it was literally true.

I then proceeded to point out the same in my own life.

I did not intend to imply that it was easy to deal with.

(Note for others reading this there have been messages off list about this)


Re: stackoverflow vs the world (and perl6-users)

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 2:29 PM, The Sidhekin  wrote:
>
>
> On Tue, Jun 12, 2018 at 9:18 PM, Brad Gilbert  wrote:
>>
>> On Tue, Jun 12, 2018 at 1:19 PM, Joseph Brenner  wrote:
>> > Attention conservation:  it's unlikely I'm going to say something
>> > interesting you haven't thought of already.
>> >
>> > A side-discussion that came up here: should you ask questions here, or
>> > at stackoverflow (or both here *and* at stackoverflow).
>> >
>> > I understand the argument that it's better to talk about perl in
>> > public where non-perl might see it (to help counter that "perl is
>> > dead" impression that's floating around).  Getting more involved with
>> > stackoverflow has been on my list for a long time... and yet I haven't
>> > gotten to it.  Why not?
>> >
>> > (1) The barrier at stackoverflow to a beginner is probably higher than
>> > you think it is-- it's not at all obvious what you're allowed to do
>> > and what you're not at the outset.
>>
>> The barrier is non-existent.
>
>
>
>   Your failure of imagination does not make that barrier any less real.
>

I have only ever heard about speculated and imagined barriers.

Note that even being blind shouldn't be a barrier, as they try hard
to make it accessible.

As long as you follow the rules, there isn't much of anything slowing you down.

Basically I don't think I need to imagine them because I have already
heard/read them.


Re: stackoverflow vs the world (and perl6-users)

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 2:42 PM, Brandon Allbery  wrote:
> On Tue, Jun 12, 2018 at 3:38 PM Brad Gilbert  wrote:
>>
>> > The barrier is non-existent.
>>
>> I have only ever heard about speculated and imagined barriers.
>
>
> This is not proof that such barriers don't exist. I hit the magic 2 mark
> and lasted less than a week afterward because the rules suddenly changed in
> a way that induced severe social anxiety. Again, this is not something
> "fixable", not on my end.

The rules did not change.
It's just features that you didn't have before became available.
You are free to ignore them.

If you can't ignore them, you could try bringing it up on
meta.stackoverflow.com,
and maybe someone there could do something to improve it for you.

>
> You are not everyone. Don't assume what works for you necessarily works for
> everyone. Or that there are quick and accessible workarounds for everyone.
>

The barrier is not with Stack Overflow. (←What I obviously meant)
The barrier is within you.

I should know I have some myself.

For example, I have never gotten a job by myself.
(Well there is the one time where they called on the phone, but I didn't
pick it up because I didn't recognize the number.)

I have also never been on a date as it gives me too much anxiety to ask.
(There was one gal that I was absolutely smitten with, who I
was also absolutely sure wanted me to ask her out, but was unable to.)


Should I say that the barrier is with women (incel), or with myself?

---

That's not to say there isn't something that other people could do to reduce
the barrier. I don't think anybody can do that if they don't know it exists.

If you at least tell me what changes could help, I could bring it up on meta.


Re: stackoverflow vs the world (and perl6-users)

2018-06-12 Thread Brad Gilbert
On Tue, Jun 12, 2018 at 1:19 PM, Joseph Brenner  wrote:
> Attention conservation:  it's unlikely I'm going to say something
> interesting you haven't thought of already.
>
> A side-discussion that came up here: should you ask questions here, or
> at stackoverflow (or both here *and* at stackoverflow).
>
> I understand the argument that it's better to talk about perl in
> public where non-perl might see it (to help counter that "perl is
> dead" impression that's floating around).  Getting more involved with
> stackoverflow has been on my list for a long time... and yet I haven't
> gotten to it.  Why not?
>
> (1) The barrier at stackoverflow to a beginner is probably higher than
> you think it is-- it's not at all obvious what you're allowed to do
> and what you're not at the outset.

The barrier is non-existent.

You don't have to even create an account to post on it.
(You should if you want to be able to edit or delete your posts after
your cookie expires.)

If you have code that you can't get to work the way you think it should,
it is the right place to ask. All other questions are off topic.

On the ask question page they have a list of the rules.
I think they may even have a mini tutorial for first-time users.

> (2) Stackoverflow is centralized, I don't know really who's in control
> of it (and early on I had the impression they were a bunch of
> microsofties).  Email has the virtue of being federated-- or it would
> be if we weren't all using gmail-- and if there's a web archive it's
> also indexed.

Stack Overflow is from Fog Creek Software.
See https://stackoverflow.com/company

They also regularly provide bulk downloads of all the publically available data.

> (3) Stackoverflow may be "well indexed", but I haven't noticed this
> being very helpful for perl6 where many things are huffmaned down
> below the level where they can work as grep crumbs.  E.g. "does" vs.
> "but" and perhaps worse "=" vs. ":=".

That is fair, but other languages have the same problem.
Since a lot of them use Stack Overflow, they know they can search
there instead.

> (4) I've seen some complaints about stackoverflow moderators that
> seemed all-too-familiar-- power tripping for the sake of it.  They
> seem to be a bit trigger-happy about shutting down interesting and
> illuminating discussion ("this is all just matter of opinion!").
> It's not at all unusual to do a web search on a question and end up at
> a stackoverflow page that a moderator has marked as "Closed".

Very few questions are closed by moderators.
The vast majority are voted to be closed by users.
In fact some moderators refuse to vote to close iffy questions,
because their vote counts as 5 regular users.

If you ask what is the best module for doing X, that is considered
to broad.
If you are having trouble using a particular module, then it is not.

If you ask a homework question, then it is too broad.
If you ask what is wrong with my homework it isn't.
(it may be closed anyway if enough users think it shouldn't be there)

The reasoning for this is to prevent it from becoming another
Yahoo! answers. (They have said this many times on the podcast)

Also note that you are still allowed to edit it to follow the rules.
If enough people agree that you have sufficiently fixed it, they
can vote to reopen it.

If it is sufficiently bad, users will vote to delete it.

Moderators are also elected. So if one of them abuses their
power they risk losing their moderator privileges.

The main purpose of moderators is to fix problems the regular
system doesn't work sufficiently for.
(Spam, bulk voting, sock puppet accounts, abusive speech,
joining accounts, etc)

Basically your remark about mods power tripping is baseless.
The only real problem is that some people don't like the rules.
(Even though most rules have been added by user demand.)

> (5) I question how much it improves visibility to post perl6 material
> at stackoverflow: there's so much stuff there very few people look at
> the place as a whole: the only people likely to look at a perl6
> discussion are the people who are already interested in perl6.

Stack Overflow puts out data about how many questions get asked
for each language. So by putting it there we influence their stats.

This is the main reason JJ keeps saying to post there.

---

Note that I have been following the development of StackOverflow
since before they had a private beta. (podcasts)

I'm user number 1337 by the way.
I may be the only Perl programmer to receive the Beta badge.


Re: How do I remove leading zeros?

2018-06-13 Thread Brad Gilbert
On Wed, Jun 13, 2018 at 1:09 PM ToddAndMargo  wrote:
>
> On 06/13/2018 11:06 AM, ToddAndMargo wrote:
> > On 06/13/2018 11:03 AM, ToddAndMargo wrote:
> >> On 06/13/2018 11:00 AM, Larry Wall wrote:
>
> > $ p6 'my $x = "01.000.103.006.10"; $x ~~ s:g/«0+)>\d//; say "$x"'
> > 1.0.103.6.10
>
> Hi Larry,
>
>  How did you get thee "«" character to appear?  And
> what does it mean?
>

The way I type them is [compose] [<] [<], which is nice because their
ASCII equivalent is <<

It means match a word boundary with the word being on the right side.

> say 'ABC DEF ' ~~ m:g/ << . /
(「A」 「D」)
> say 'ABC DEF ' ~~ m:g/ >> . /
(「 」 「 」)


Re: An operation first awaited

2018-05-28 Thread Brad Gilbert
Comments inline.

On Mon, May 28, 2018 at 2:02 AM, Norman Gaywood  wrote:
> T""his simple program creates a thread to read a directory with dir() and
> place the files on a channel. $N worker threads read that channel and
> "process" (prints) the files. But I'm getting this "An operation first
> awaited:" error.
>
> I've read the traps page about this error several times, but still can't
> make sense of it. Can some explain what's going on here?
>
> The directory contents:
> $ ls
> a  b  c  traverse-dir0.p6
>
> Running the program:
> $ ./traverse-dir0.p6
> traverse-dir0.p6
> a
> b
> c
> An operation first awaited:
>   in sub MAIN at ./traverse-dir0.p6 line 24
>   in block  at ./traverse-dir0.p6 line 5
>
> Died with the exception:
> Cannot find method 'path': no method cache and no .^find_method
>   in block  at ./traverse-dir0.p6 line 16
>
> The program:
> $ cat traverse-dir0.p6
> #!/usr/bin/env perl6
> # There is a thread to populate $dir-channel by reading filenames in a
> directory with dir()
> # and $N worker threads to read the filenames from the $dir-channel.
>
> sub MAIN( Str $dir = ".", Int :$N = 4 ) {
>
> my $dir-channel = Channel.new();
> my $dir-read = start {
> $dir-channel.send( $_ ) for dir $dir;
> $dir-channel.close;
> }
>
> my @workers = (^$N).map: {
> start {
> while my $file = $dir-channel.receive() {
> say $file.path;
> }
> CATCH {
> when X::Channel::ReceiveOnClosed { .resume }

--

What did you expect to happen if you resumed?

Because I expect it to try to run `say $file.path;` with invalid data.
You can just remove the `.resume` and it works.

--

> }
> }
> }
>
> await $dir-read, @workers;
> }

There is no need to await for $dir-read, as the workers won't finish
until it's done anyway.

---

Anyway I would use a `react` block.

my @workers = (^$N).map: {
start react whenever $dir-channel -> $file {
say $file.path;
}
}

Note that `start` and `react` don't need {}, but you can use them if neccesary.


my @workers = (^$N).map: {
start {
say 'started';

react {
say 'reacting';

whenever Promise.in(½) { say '½ second has elapsed' }

whenever $dir-channel -> $file {
say $file.path;
}
}
}
}


Re: my keeper on random numbers

2018-05-26 Thread Brad Gilbert
On Sat, May 26, 2018 at 10:59 PM, ToddAndMargo  wrote:
> On 05/26/2018 05:10 AM, Brian Duggan wrote:
>>>
>>> To convert to an positive integer, use truncate:
>>>  $ p6 'say 1000.rand.truncate;'
>>>  876
>>
>>
>> or use pick:
>>
>> perl6 -e 'say (^1000).pick'
>> 209
>>
>> Brian
>
>
> Hi Brian,
>
> What does
>
> (^1000)
>
> mean?

`^1000` is short for `0..^1000` which is syntax for
`Range.new( 0, 1000, :excludes-max )`


Re: need second pair of eyes

2018-06-03 Thread Brad Gilbert
It's -I. not -I

On Sun, Jun 3, 2018 at 5:05 PM, ToddAndMargo  wrote:
> On 06/03/2018 02:54 PM, Brad Gilbert wrote:
>>
>> You can use q[./] instead of \'./\'
>> (especially useful so that it will work on both Windows and Unix
>>
>> But in this case it is even better to use -I and -M
>>
>>  p6 -I. -MRunNoShell -e '( my $a, my $b ) =
>>   RunNoShell::RunNoShell("ls *.pm6"); say $a;'
>>
>> On Sun, Jun 3, 2018 at 4:47 PM, ToddAndMargo 
>> wrote:
>>>>>
>>>>> On Sun, Jun 3, 2018 at 5:28 PM ToddAndMargo >>>> <mailto:toddandma...@zoho.com>> wrote:
>>>>>
>>>>>  Hi All,
>>>>>
>>>>>  What am I doing wrong here?
>>>>>
>>>>>
>>>>> $ p6 'lib \'./\'; use RunNoShell; ( my $a, my $b ) =
>>>>>  RunNoShell::RunNoShell("ls *.pm6"); say $a;'
>>>>>
>>>>> bash: syntax error near unexpected token `='
>>>>>
>>>>>  Huh ???
>>>>>
>>>>>
>>>>>  This is RunNoShell.pm6
>>>>>
>>>>>sub RunNoShell ( $RunString ) is export {
>>>>>   ...
>>>>>   return ( $ReturnStr, $RtnCode );
>>>>>}
>>>>>
>>>>>  Many thanks,
>>>>>  -T
>>>
>>>
>>>
>>> On 06/03/2018 02:36 PM, Brandon Allbery wrote:
>>>>
>>>>
>>>> bash doesn't like nested single quotes, even with escapes. So the first
>>>> \'
>>>> gave you a literal backslash and ended the quoted part, then the second
>>>> \'
>>>> gave you a literal ' and continued without quoting. The final ' would
>>>> then
>>>> open a new quoted string, but bash doesn't get that far because it sees
>>>> the
>>>> (now unquoted) parentheses and tries to parse them as a command
>>>> expansion.
>>>>
>>>> allbery@pyanfar ~/Downloads $ echo 'x\'y\'z'
>>>>   > ^C
>>>>
>>>> Note that it thinks it's still in a quoted string and wants me to
>>>> continue.
>>>>
>>>
>>> p6 does not like `lib ./`,  meaning use the current directory
>>> without the single quotes.  Any work around?
>
>
> It needs the path, which is ./
>
> $ perl6 -I -MRunNoShell '( my $a, my $b ) = RunNoShell::RunNoShell("ls
> \*.pm6"); say $a;'
>
> Could not open ( my $a, my $b ) = RunNoShell::RunNoShell("ls \*.pm6"); say
> $a;. Failed to stat file: no such file or directory


Re: need second pair of eyes

2018-06-03 Thread Brad Gilbert
You can use q[./] instead of \'./\'
(especially useful so that it will work on both Windows and Unix

But in this case it is even better to use -I and -M

p6 -I. -MRunNoShell -e '( my $a, my $b ) =
 RunNoShell::RunNoShell("ls *.pm6"); say $a;'

On Sun, Jun 3, 2018 at 4:47 PM, ToddAndMargo  wrote:
>>> On Sun, Jun 3, 2018 at 5:28 PM ToddAndMargo >> > wrote:
>>>
>>> Hi All,
>>>
>>> What am I doing wrong here?
>>>
>>>
>>>$ p6 'lib \'./\'; use RunNoShell; ( my $a, my $b ) =
>>> RunNoShell::RunNoShell("ls *.pm6"); say $a;'
>>>
>>>bash: syntax error near unexpected token `='
>>>
>>> Huh ???
>>>
>>>
>>> This is RunNoShell.pm6
>>>
>>>   sub RunNoShell ( $RunString ) is export {
>>>  ...
>>>  return ( $ReturnStr, $RtnCode );
>>>   }
>>>
>>> Many thanks,
>>> -T
>
>
> On 06/03/2018 02:36 PM, Brandon Allbery wrote:
>>
>> bash doesn't like nested single quotes, even with escapes. So the first \'
>> gave you a literal backslash and ended the quoted part, then the second \'
>> gave you a literal ' and continued without quoting. The final ' would then
>> open a new quoted string, but bash doesn't get that far because it sees the
>> (now unquoted) parentheses and tries to parse them as a command expansion.
>>
>> allbery@pyanfar ~/Downloads $ echo 'x\'y\'z'
>>  > ^C
>>
>> Note that it thinks it's still in a quoted string and wants me to
>> continue.
>>
>
> p6 does not like `lib ./`,  meaning use the current directory
> without the single quotes.  Any work around?


Re: <> question

2018-06-03 Thread Brad Gilbert
On Sun, Jun 3, 2018 at 3:08 PM, ToddAndMargo  wrote:

> On 06/03/2018 11:01 AM, Brandon Allbery wrote:
>
>> Is there something missing in the examples at the link?
>>
>
> Well, a bit.  When I see
>
> chmod 0o755, ;
>
> I think `myfile1` and `myfile2` are "functions", not
> data.
>

They aren't, they are a list of strings.

`< a b c >` is short for `qw< a b c>` which is short for `Q :single :words
< a b c >`

basically `' a b c '.words()`

see https://docs.perl6.org/language/quoting

So the above is really the same as:

chmod 0o755, ( 'myfile1',  'myfile2' );


Re: using run

2018-06-21 Thread Brad Gilbert
:out can take an argument

On Wed, Jun 20, 2018 at 10:32 AM Theo van den Heuvel
 wrote:
>
> Hi all,
>
> trying to make sense of the documentation on run:
> https://docs.perl6.org/routine/run.
> In particular the last part. I don't  understand the adverbs :out and :
> err there.
> Can I set it up so that the output is piped into a file directly? If so
> how would I write that?
>
> I know I could use shell for that, but I doubt that is necessary.
>
> [On first reading I found the doc confusing because it start with a
> hairy example. WHy would anyone wish to write to a file named
> '>foo.txt'? How can that be the first example?]
>

my $fh = open 'foo.txt', :w;
run 'echo', 'foo bar baz', :out($fh);
close $fh;


Re: Force integers in an array?

2018-08-06 Thread Brad Gilbert
> my Int @a;
> @a[0] = '1'
Type check failed in assignment to @a; expected Int but got Str ("1")
  in block  at  line 1
On Mon, Aug 6, 2018 at 3:39 PM ToddAndMargo  wrote:
>
> Hi All,
>
> Is there a way to force all the members of an array
> to be integers and to error out is a non-integer
> is written to one of its cells?
>
>
> Many thanks,
> -T


Re: MAIN subroutine

2018-07-19 Thread Brad Gilbert
The MAIN sub executes after the mainline.

After all should MAIN be called before or after do-it('2') in the following?

sub do-it(Str $string) {
say $string;
}
do-it("1");
multi sub MAIN() {
say "This is MAIN so this should print after the mainline";
}
do-it("2");
multi sub MAIN( $ ) {
say "This is MAIN so this should print after the mainline";
}

# implicitly something like this happens at the end of the file
MAIN( |@*ARGS );

The only other possibility is that the entire mainline gets run after
MAIN, which doesn't make a lot of sense.
(As in it wouldn't make sense to even have a mainline.)

There is no way to mix the mainline and running MAIN without making it
special case.
One goal of the design of Perl 6 is to reduce special cases.

Running a something like a MAIN subroutine at the end of the file is
actually somewhat common to do in Perl 5.
So there is some precedent for the way it works.

On Thu, Jul 19, 2018 at 4:31 PM Laurent Rosenfeld via perl6-users
 wrote:
>
> Hi folks,
>
> The documentation for the MAIN sub says that "the sub with the special name 
> MAIN is executed after all relevant phasers."
>
> My understanding is that MAIN automatically executes before any code other 
> than phasers happening at compile time or at the end or right after the end 
> of compilation. It seems that this is not the case. It seems that my 
> perception is wrong and that code not belonging to any sub is executed before 
> MAIN.
>
> For example, take this code:
>
> sub execute_after_main(Str $string) {
> say "this $string after MAIN?";
> }
> execute_after_main("1");
>
> sub MAIN() {
> say "This is MAIN so this should print first";
> }
> execute_after_main("2");
>
> This prints the following:
>
> this 1 after MAIN?
> this 2 after MAIN?
> This is MAIN so this should print first
>
> I was expecting the MAIN message to be printed first.
>
> Did I miss something? Is my understanding wrong? I'd never seen that, but I 
> guess all my scripts using MAIN had all the code in subs called from MAIN. So 
> maybe I've never hit that case.
>
> Cheers,
> Laurent.


Re: Bailador vs. Cro

2018-07-09 Thread Brad Gilbert
Bailador is based on Perl 5's Dancer which is based on Sinatra (Ruby).
(bailador is spanish for dancer)

Cro on the other hand was designed specifically around the features
that are in Perl 6.
This can make things more intuitive for someone proficient in Perl 6.
It might also make it easier to explore the way Perl 6 does things,
for beginners.

On Mon, Jul 9, 2018 at 6:27 AM Patrick Spek via perl6-users
 wrote:
>
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA256
>
> I've only done some very basic stuff with both Cro and Bailador. From
> what I can tell, Cro requires less code to get something going in, but
> Bailador is easier to get a regular MVC model working in.
>
> Have you read through the Cro SPA tutorial?
> https://cro.services/docs/intro/spa-with-cro
>
> It details setup for an API with a React+Redux frontend.
>
> On Mon, 9 Jul 2018 03:01:34 +0200
> mimosinnet  wrote:
>
> > Hi all,
> >
> > Appart from pure hobbyist pleasure, I use Perl for some personal web
> > development. I have (solely) used Mojolicious, really had fun, and
> > learned Perl using it. I have been for some time looking for a Perl6
> > framework for web development (Perl6 bewitched me), and Bailador
> > looks like an attractive Perl6 starting point.
> >
> > While trying to build an application with Bailador, I came across
> > with Cro. While it looked quite complicated at the beginning, after
> > watching Jonathan Worthington presentation [1] Cro looks quite
> > versatile, close to new Perl6 features and very Promising ("anything
> > can be put behind a Promise, but they can also be broken"). This
> > weekend, I have been trying to build a simple web application with
> > Cro [2], and it more or less worked out (and learned a lot of Perl6).
> >
> > Before investing more time in this project, I wonder if you have any
> > advice or suggestions on Bailador, Cro (or another framework like
> > Hiker [3]). Also, I would appreciate if you could point to some
> > working examples (like [4]  or [5] ).
> >
> > Many thanks!
> >
> > [1] https://www.youtube.com/watch?v=6CsBDnTUJ3A
> > [2] https://github.com/mimosinnet/Cro-Personal-Web
> > [3] https://github.com/tony-o/perl6-hiker
> > [4] https://github.com/lancew/MyJudo
> > [5] https://github.com/szabgab/Perl6-Maven
> >
>
> -BEGIN PGP SIGNATURE-
>
> iQEzBAEBCAAdFiEE4eL662U9iK2ST2MqN/W6H45XOE8FAltDRkYACgkQN/W6H45X
> OE/plQf9H4WsdaYSnG44JFUBMWlPuS7RAjbeVmZw7SQ2nj7buBmDpQqteu7XdBY7
> 659myZLGQuBjC9c3yeQqWycdF3u9pAvyP9YNLWNlTGcwTv3ODfuxoHNCg+Xbf+zK
> 00xBsaebyvU32904w7I/CYueQIzVGxGhnuvtFKnisyIs2qy/EzxlSGNLk75yj4J0
> R0nta5YD/cH5X66zbyvQ7grd4j7fh/VlhiGZx2z7VF/mLJxfTPIHUjflgSjNDioC
> VoUXAfi++jPN6GnMFqkvmtdMZZMz39/H1w7HkqoSF15z2wH61a2wYrwoJvSBgc4c
> xVDJ1oIg8vmt80f7DTcXzmUMkSk6pA==
> =KSuY
> -END PGP SIGNATURE-


Re: Using HashBags

2018-04-08 Thread Brad Gilbert
You can do the following

   my %b is BagHash = …

or

my %b := bag …

On Sun, Apr 8, 2018 at 10:54 AM, Vittore Scolari
 wrote:
> I answer myself: with % you get an Hash
>
> On Sun, Apr 8, 2018 at 5:53 PM, Vittore Scolari 
> wrote:
>>
>> Wouldn't here be better to use the % sigil?
>>
>> my %docents = bag @rows.map: -> @row {@row[0] xx @row[1]};
>>
>>
>>
>> On Sat, Apr 7, 2018 at 1:02 PM, Fernando Santagata
>>  wrote:
>>>
>>> Hi,
>>>
>>> I'm not sure that I've understood what you need.
>>> If you get that array of arrays from a another process @rows and you wish
>>> to convert it into a Bag you can do this:
>>>
>>> my @rows = [["JF", 1], ["JF", 2], ["MM", 2], ["MPu", 2], ["MM", 2],
>>> ["FE", 2], ["FV", 2], ["MPu", 2], ["JP", 2], ["JP", 2], ["FV", 2], ["FV",
>>> 2], ["JF", 2], ["MM", 2], ["MPu", 2], ["MM", 2], ["FE", 2], ["FV", 2],
>>> ["MPu", 2], ["JP", 2], ["JP", 2], ["JF", 4]];
>>> my Bag $docents = bag @rows.map: -> @row {@row[0] xx @row[1]};
>>> dd $docents;
>>>
>>> # Bag $docents = ("JP"=>8,"FV"=>8,"FE"=>4,"MPu"=>8,"MM"=>8,"JF"=>9).Bag
>>>
>>> Otherwise you can start collecting those pairs into a Bag from the start,
>>> but we would need more details then.
>>>
>>> HTH
>>>
>>>
>>> On Sat, Apr 7, 2018 at 12:10 PM, mimosinnet  wrote:

 Hi all,

 I do not seem to be able to get this done with the Bag or BagHash type:

 ---
 dd @rows;

> Output: Array @rows = [["JF", 1], ["JF", 2], ["MM", 2], ["MPu", 2],
> ["MM", 2], ["FE", 2], ["FV", 2], ["MPu", 2], ["JP", 2], ["JP", 2], ["FV",
> 2], ["FV", 2], ["JF", 2], ["MM", 2], ["MPu", 2], ["MM", 2], ["FE", 2],
> ["FV", 2], ["MPu", 2], ["JP", 2], ["JP", 2], ["JF", 4]]


 my %docents;
 for @rows -> @row {
 %docents{ @row[0] } += @row[1];
 }

 dd %docents;

> Output: Hash %docents = {:FE(4), :FV(8), :JF(9), :JP(8), :MM(8),
> :MPu(8)}


 ---

 As I understand it, this would better be achieved with the Bag or
 BagHash type. What would be the easy way?

 Thanks!
 --
 (≧∇≦) Mimosinnet (Linux User: #463211)
>>>
>>>
>>>
>>>
>>> --
>>> Fernando Santagata
>>
>>
>


Re: Could this be any more obscure?

2018-09-27 Thread Brad Gilbert
In Perl 6 most normal operators are subroutines:

@a[1..3]
:« [  ] »( @a,1..3 ) # same as above

Since they are just subroutines they often just call something else.

# an overly simplified version
sub postcircumfix:« [  ] » ( @array, **@indicies ) {
gather {
for @indicies -> $index {
take @array.AT-POS( $index )
}
}
}

When you define such a subroutine for the first time, it modifies the parser.

In the case of :« [  ] », it can take ANY VALUE as its
first argument.
On `Positional` arguments it calls `.AT-POS`.
If it isn't `Positional`, it will pretend that it is a list of one value.

   1[0];   # pretend that `1` is the same as `(1,)`

This means it can be found everywhere throughout the language.

---

We do not want to describe every bit of the language that interacts
with the `.words` method.
This is because that would be the entire language on one page.

When you talked about [], this is inadvertently what you asked for.

---

In the case of the `.words()` document we say that it is called on
`Str` and returns a `Seq`.
(The docs were wrong about it returning a `Positional`)

We document that it returns the parts of the string that aren't whitespace.

We document that you can give a limit to how many values it returns.
(arguably, this isn't needed because you can just call `.head($limit)` instead)

If we changed it to `selection` it would make it seem more complicated
than it really is.
Selection could mean that it could select the second and third values.
`.words()` doesn't do that.

The closest synonyms would be:
cap
maximum
upper bound
cutoff point
farthest point
end
max count

We do not document every single operator that operates on a `Seq`, on that page.
(Almost every single one of them.)
Again, [] is one of them.

We do not document on that page all of the methods of `Seq`.
(There is a page specifically for that)

On Wed, Sep 26, 2018 at 9:18 PM ToddAndMargo  wrote:
>
> On 9/26/18 7:11 PM, Brandon Allbery wrote:
> > That's not helping. What didn't you understand?
>
> >>  It just improves error messages.
>
> My understanding it that if it uses "--Positinal"
> I can use []


Re: slurp so many?

2018-10-07 Thread Brad Gilbert
I think the easiest way to get a 400 characters from a file is with
.comb() on the file.

   'example.txt'.IO.comb(400).head()
On Sun, Oct 7, 2018 at 6:42 PM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> I use `slurp` all the time, so of course, I can't
> make heads or tails out of
>
>   https://docs.perl6.org/routine/slurp
>
> I want to slurp the first 400 characters of
> a file and close the handle.  Am I missing a
> `so many` parameter somewhere?
>
> Many thanks,
> -T


Re: need --> help

2018-10-12 Thread Brad Gilbert
That would be `List`

sub RtnOrd( Str $Char --> List ){ $Char, ord($Char) }
say RtnOrd "A"
# (A 65)

On Fri, Oct 12, 2018 at 3:14 PM ToddAndMargo via perl6-users <
perl6-users@perl.org> wrote:

> >> On Fri, Oct 12, 2018 at 3:32 PM ToddAndMargo via perl6-users
> >> mailto:perl6-users@perl.org>> wrote:
> >>
> >>
> >> But this does not?
> >>
> >>   $ p6 'sub RtnOrd( Str $Char --> Str, Int ){return $Char,
> >> ord($Char)}; say RtnOrd "A";'
> >>
> >>   ===SORRY!=== Error while compiling -e
> >>   Malformed return value (return constraints only allowed at the
> >> end
> >> of the signature)
> >>   at -e:1
> >>   --> sub RtnOrd( Str $Char --> Str⏏, Int ){return $Char,
> >> ord($Char)}; say R
>
> On 10/12/18 12:52 PM, Curt Tilmes wrote:
> > You could make a subset for the List your're trying to return:
> >
> > subset liststrint of List where .[0] ~~ Str && .[1] ~~ Int;
> > sub RtnOrd( Str $Char --> liststrint) ...
>
>
> I am confused.
>
> I want to get the --> syntax correct for `return $Char, ord($Char)`
>


Re: Malformed UTF-8 ???

2018-10-13 Thread Brad Gilbert
Change the encoding to `utf8-c8` to let the invalid unicode through.

or use binary methods.

or make sure it isn't in some other encoding.
On Sat, Oct 13, 2018 at 5:18 AM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
>   if  $StdOut  { $ReturnStr = $$proc.out.slurp-rest; }
>
> gives me
>
>   Malformed UTF-8
>
> How do I clean up $$proc.out.slurp-rest ??
>
> Many thanks,
> -T


Re: what type $in,$out and $err is

2018-10-28 Thread Brad Gilbert
That is talking about the arguments for the method/subroutine call.

The way you pass in $in as True, is to add `:in`

run "cat", "-n", :in, :out;

The `:in` and `:out` are exactly the same as `:in(True)` `:out(True)`

run "cat", "-n", :in(True), :out(True);

Which is also the same as `in => True`

run "cat", "-n", in => True, out => True;

There is even a shortcut for `in => $in`

my $in = True;
my $out = True;

run "cat", "-n", :$in, :$out;
run "cat", "-n", in => $in, out => $out;
run "cat", "-n", :in($in), :out($out);

---

Basically that is a way to indicate that you are actually interested
in those filehandles,
and for the routine to set them up for you.
On Sun, Oct 28, 2018 at 2:26 PM Xiao Yafeng  wrote:
>
> I'm curious about what type of $in is on Proc class. As described in perl6doc:
> $in, $out and $err are the three standard streams of the
> to-be-launched program, and default to "-" meaning they inherit the
> stream from the parent process. Setting one (or more) of them to True
> makes the stream available as an IO::Pipe object of the same name,
> like for example $proc.out.
>
> I mean, if $in is IO::Pipe object, how can I pass it True?
>
> > my IO::Pipe $bb = True;
> Type check failed in assignment to $bb; expected IO::Pipe but got Bool
> (Bool::True)
>   in block  at  line 4
>
> I'm interested in the underlying mechanics of  it. Please enlighten me.
>
> Besides, just curious, why choose '_' as default it looks strange


Re: Exception Handling, DivideByZero

2018-10-29 Thread Brad Gilbert
.WHAT gives you the actual type, whereas .^name gives you a string
that is the name.

In Perl6 types are things you can pass around; which is good because
you can have more than one with the same name.

sub bar (){
  my class Foo {  }
}
sub baz (){
  my class Foo {  }
}

my $a = bar().new();

bar() === $a.^name; # False (one is a Foo type object, the other a string)
bar() === $a.WHAT; # True (both are the Foo type object)

bar().^name === baz().^name; # True (but they are different types)
bar().WHAT === baz().WHAT; # False (both are type objects, but
they are different types)

"".WHAT =:= Str; # True (both are the Str type object)

Basically think about .WHAT as being the Perl6 equivalent of `typeof()`.
On Mon, Oct 29, 2018 at 12:12 PM Joseph Brenner  wrote:
>
> Brandon Allbery  wrote:
> > Two issues:
> >
> > (1) all standard exceptions are in or under the X:: namespace.
> >
> > (2) .WHAT doesn't show names with their namespaces, whereas .^name does.
> >
> > pyanfar Z$ 6 'my $r = 4/0; say $r; CATCH {default {say .^name}}'
> > X::Numeric::DivideByZero
>
> Thanks.  I didn't get that the behavior of WHAT and ^name were that different.
>
>
>
> > On Mon, Oct 29, 2018 at 1:04 PM Joseph Brenner  wrote:
> >
> >> I was just looking into doing some finer-grained exception handling,
> >> so I tried this:
> >>
> >>use v6;
> >>try {
> >>my $result = 4/0;
> >>say "result: $result";
> >>CATCH {
> >>#when DivideByZero { say "Oh, you know."; }
> >>default { say .WHAT; .Str.say } # (DivideByZero)   Attempt
> >> to divide 4 by zero using div
> >>}
> >>}
> >>
> >> The first time through, The .WHAT tells me I've got
> >> "DivideByZero", and so I added the line that's commented out
> >> here, at which point I got the error:
> >>
> >>===SORRY!===
> >>Function 'DivideByZero' needs parens to avoid gobbling block (or
> >> perhaps it's a class that's not declared or available in this scope?)
> >>
> >> Putting parens around (DivideByZero) doesn't help:
> >>
> >>Undeclared name:
> >>   DivideByZero used at line 12
> >>
> >> My impression was this would just work from looking
> >> at the examples using things like X::AdHoc here:
> >>
> >>   https://docs.perl6.org/language/exceptions
> >>
> >
> >
> > --
> > brandon s allbery kf8nh
> > allber...@gmail.com
> >


Re: <> thank you

2018-10-05 Thread Brad Gilbert
<> is part of the quoting sub-language

It is short for

q:w' a b c d '

which is short for

q:words' a b c d '

Note that you can add spaces

q :words ' a b c d '

Even this is short.
I'm going to show you various ways of writing the exact same thing

q :w(1) ' a b c d '
q :w(True) ' a b c d '
Q :q :w ' a b c d '
Q :single :words ' a b c d '
Q :single(True) :words(True) ' a b c d '

Note that :Identifier is short for :Identifier(True)

To learn more about the quoting sub-language read:

https://docs.perl6.org/language/quoting
On Fri, Oct 5, 2018 at 7:00 AM Todd Chester  wrote:
>
>
>
> On 10/5/18 4:51 AM, Laurent Rosenfeld via perl6-users wrote:
> > You don't even need the quotes:
> >
> >  > say [3,1];
> > (Nil cd)
> >  >
>
> Hi Laurent,
>
> A thing of beauty!
>
> Not to ask to stupid a question (when has that ever
> stooped me), but since [] is considered a subroutine,
> is <> also considered a subroutine too? If so, what
> is it called?
>
> -T


Re: bitwise or?

2018-10-05 Thread Brad Gilbert
Note that = is actually a meta operator that can take an infix
operator as an argument

So

$a += 1

is really short for

$a [+]= 1

On Fri, Oct 5, 2018 at 1:02 AM Todd Chester  wrote:
>
>
>
> On 10/4/18 12:13 PM, Brandon Allbery wrote:
> > It's fine syntactically, but I think has no effect because it'd be '$v =
> > $v' after the '+|='. Conceivably some future version of rakudo could
> > warn about it having no effect.
>
> That explains it.  Thank you!


Re: eof ?

2018-10-09 Thread Brad Gilbert
On Tue, Oct 9, 2018 at 8:31 AM Curt Tilmes  wrote:
>
> On Tue, Oct 9, 2018 at 9:27 AM Laurent Rosenfeld via perl6-users 
>  wrote:
>>
>> This:
>> my $f = $fh.lines;
>> will slurp all the lines into $f (but you can still access the individual 
>> items with something like $f[4]).
>
>
> Is that true?  I supposed that it would hold the Seq as a scalar 
> (un-iterated) Seq.

No it isn't true.
It stores the Seq in $f.

The following doesn't print anything.

my $f = 'example.txt'.IO.lines.map(*.say); Nil

(Note that I added `Nil` so that if someone tried this in the REPL, it
doesn't try to `say` what's in `$f`.)

What it does do is make the Seq marked as an item, so this only runs
one loop, and doesn't run the `.map` code.

for $f { Nil }

But both of these will:

for @$f { Nil }
for $f<> { Nil }


> I know that my @f = $fh.lines will slurp it all, but I thought you could 
> avoid that by assigning it to a scalar.
>
> Curt
>


Re: Use of the --output flag

2018-10-09 Thread Brad Gilbert
My guess is that this is a bug.

You can work around it by adding

my $*OUT = q[test].IO.open(:w);

in front of the code.
On Tue, Oct 9, 2018 at 8:18 AM Simon Proctor  wrote:
>
> So... I'm working through some notes for a talk on Thursday and I am trying 
> to work out how the --output flag is supposed to work.
>
> I would expect this to create a file called test and print "Hi\n" in it :
>
> perl6 --output=test -e 'say "Hi"'
>
> But instead I got Hi printed to the command line and an error :
>
> Use of Nil in string context
>   in any print at gen/moar/stage2/NQPCORE.setting line 850
>
> Trying use it on a sime file (say "Hi") and it also doesn't do that.
>
> (Note that the test file is created but it's empty).
>
> Any ideas?
>
> --
> Simon Proctor
> Cognoscite aliquid novum cotidie
>
> http://www.khanate.co.uk/


Re: eof ?

2018-10-09 Thread Brad Gilbert
That isn't the syntax for a loop local variable in Perl 6.

You are trying to use the Perl 5 syntax, which is not going to work in Perl 6

This is the Perl 5 code you are trying to write

while( my $f = readline $fh ){ say "$f\n"}

Which actually would turn into the following by Perl 5 compiler

while( defined( my $f = readline $fh ) ){ say "$f\n"}

If you want something that works the same in Perl 6:

while $fh.get -> $f { say $f }

---

The reason you use `while` in Perl 5 is to prevent `for` from reading
the entire file before looping.

# Perl 5
# reads in entire file before doing any work on it
for my $f (readline $fh){ say $f }
# (the reason is that readline is in list context)

This is not a problem in Perl 6

# Perl 6
# loops over a Seq which only reads enough data to get the next line
for $fh.lines -> $f { say $f }
On Tue, Oct 9, 2018 at 7:49 AM ToddAndMargo via perl6-users
 wrote:
>
> On 10/9/18 5:42 AM, Fernando Santagata wrote:
> > The answer Laurent Roseenfeld gave you works for read and readchars as well.
> > Save the following lines in a file and run it (try and change .read into
> > .readchars too); it will output a series of 10-byte long Buf[uint8]s,
> > until it reaches the end of file.
> >
> > #!/usr/bin/env perl6
> > given $*PROGRAM-NAME.IO.open {
> >while my $bytes = .read: 10 {
> >  $bytes.say;
> >}
> > }
> >
> > On Tue, Oct 9, 2018 at 10:17 AM ToddAndMargo via perl6-users
> > mailto:perl6-users@perl.org>> wrote:
> >
> > On 10/9/18 1:02 AM, ToddAndMargo via perl6-users wrote:
> >  > Hi All,
> >  >
> >  > When reading a text file
> >  > https://docs.perl6.org/routine/lines
> >  > seems pretty straight forward.
> >  >
> >  > Question:  How do I tell when I when I have
> >  > reached the EOF (End Of File)?
> >  >
> >  > Many thanks,
> >  > -T
> >
> > Please expand the question to include `read` and `readchars`.
> >
> >
> >
> > --
> > Fernando Santagata
>
> Hi Frenando,
>
> Thank you for the help!
>
> I am not getting anywhere with `.lines`.  Read the whole thing in the
> first line.
>
> $ p6 'my $fh=open "/home/linuxutil/WhoIsMySub.pl6", :r;  while my $f =
> $fh.lines { say "$f\n"}; $fh.close;'
>
> #!/usr/bin/env perl6  sub f() { put &?ROUTINE.gist; };  sub abc () {
> say "This subroutine's ID is ", f; print "\n";  &?ROUTINE.gist
> ~~ m/' '(.*?)' '\(/;  my $SubName = $0; say "This subroutine is
> called $SubName"; }  abc;
>
> -T


Re: A problem with native CArrays

2018-09-30 Thread Brad Gilbert
The [+] works because of an optimization.

If you use the core :<+> it instead calls the .sum() method.

Since CArray has a sum method, that gets called instead.
On Sun, Sep 30, 2018 at 4:28 AM Fernando Santagata
 wrote:
>
> Hi,
>
> I was hunting for a bug in my code, this one:
>
> my @a := CArray[int32].new: 6,3;
> say [+] @a; # it should be "say [+] @a.list;"
>
> That statement prints "9", while changing the '+' with a '*' it generates an 
> error, as it should:
>
> Cannot resolve caller Numeric(NativeCall::Types::CArray[int32]: ); none of 
> these signatures match:
> (Mu:U \v: *%_)
>
> Is this a bug, an inconsistency, or a necessary evil?
>
> --
> Fernando Santagata


Re: Package Compile Question

2018-10-01 Thread Brad Gilbert
`Foo::Bar::<$quux>` is basically short for `::Foo::Bar::('$quux')` (except
the former is looked up at compile time)

So the way to do this is:

my $bar = 'Bar';
::Foo::( $bar ~ '::$quux' )

or

::Foo::($bar)::('$quux')

Note that the leading `::` are necessary for dynamic lookups. (Where the
name is in a variable)

On Sun, Sep 30, 2018 at 7:27 AM Richard Hogaboom 
wrote:

> This does not compile; I think it should:
>
> use v6;
>
> class Foo {
>  class Bar {
>  our $quux = 42;
>  }
> }
>
> say $Foo::Bar::quux;  # works - 42
> say Foo::Bar::<$quux>;  # works - 42
> my $bar = 'Bar';
> say $Foo::($bar)::quux;  # works - 42
>
> # shouldn't this work too?
> say Foo::($bar)::<$quux>;  # nope - won't compile
>
> # ===SORRY!=== Error while compiling
> /home/hogaboom/hogaboom/Perl6/p6ex/./p6test.p6
> # Combination of indirect name lookup and call not supported
> # at /home/hogaboom/hogaboom/Perl6/p6ex/./p6test.p6:16
> # --> say Foo::($bar)::⏏<$quux>;  # nope
> # expecting any of:
> # argument list
>
> # See https://docs.perl6.org/language/packages
> # and look at the first two sections: 'Names' and 'Package-qualified names'
>
> --
>
> rahogaboom
>


Re: routine declaration line question

2018-10-03 Thread Brad Gilbert
If a routine does not declare it's return type, absolutely anything
can be returned.

One reason may be that its return value isn't really useful.

It could be that the writer didn't think to declare it. (or didn't want to)

Another possibility is that the potential returned values are of many
different types.

---

Note that any returned value that gets ignored will get sunk.
(That means the `.sink()` method will get called)

class Baz {
method sink () { say 'the result of foo() was sunk' }
}
sub foo () {
Baz.new
}

foo(); # the result of foo() was sunk

So I suppose it is similar to Modula2, except it is up to the writer
of the class if they shake their finger at you.
On Wed, Oct 3, 2018 at 10:26 PM ToddAndMargo  wrote:
>
> >> On Wed, Oct 3, 2018 at 7:21 PM ToddAndMargo  >> > wrote:
> >>
> >>  >> On 04/10/2018 03:07, ToddAndMargo wrote:
> >>  >>> Hi All,
> >>  >>>
> >>  >>> In another thread, Timo wrote me:
> >>  >>>
> >>  >>> The "-->" part of the signature is optional. If there 
> >> isn't
> >>  >>> one, it defaults to Mu, which is the type that everything
> >>  >>> conforms to, i.e. the sub or method that either has
> >> "--> Mu"
> >>  >>> explicitly, or has it by leaving it out, may return
> >>  >>> absolutely whatever it wants.
> >>  >>>
> >>  >>> After all, the "-->" part is a constraint, and it gets
> >>  >>> validated at compile time every time a sub or method
> >>  >>> returns.
> >>  >>>
> >>  >>> I got to thinking, some routines do not return anything.  Without
> >>  >>> the "-->" constraint, how am I to determine if something is
> >>  >>> being returned?
> >>  >>>
> >>  >>> Yours in confusion,
> >>  >>> -T
> >>
> >> On 10/3/18 6:44 PM, Timo Paulssen wrote:
> >>  > I just spotted a grave mistake in my earlier mail:
> >>  >
> >>  > the --> constraints are validated at *run* time, not *compile* time;
> >>  > that's a very big difference, and an important one. Of course "every
> >>  > time a sub or method returns" doesn't make much sense if i had meant
> >>  > "compile time", but I felt i should really point it out before
> >> causing
> >>  > too much confusion.
> >>  >
> >>
> >> Hi Timo,
> >>
> >> Thank you for the help over on the chat line with IN!
> >>
> >> My confusion is not that it returns something (Mu).
> >>
> >> My confusion is "what" it returns.  And not all subs
> >> return things, like "say" and "print".
> >>
> >> I am presuming I am to pick the "what" from context
> >> from the examples?
> >>
> >> -T
>
> On 10/3/18 7:53 PM, yary wrote:
> >  > And not all subs return things, like "say" and "print".
> >
> > say and print return true if the print succeeded, just like in perl 5.
> >
> >> say say "hi";
> >
> > hi
> >
> > True
> >
> >
> > Useful if printing to a filehandle, and the file you're writing to is on
> > a volume that fills up. Or a network drive that goes away. You do check
> > for those, right?
> >
> >
> > -y
>
> Hi Yary,
>
> Ya,  my misunderstanding.  Trey just taught me that.  Home
> brew ones too.
>
> $ p6 'sub x($Str) {say $Str};say x("y");'
> y
> True
>
>
> I think where I got mixed up was not realizing that the
> things subs return can be ignored.  And it is not like I
> don't do that all the time either.  I think I just
> spaced as in Modula2, you get the finger shaken at you.
>
> Now All I have to figure out is how tot tell "what" is being
> returned.  Am I suppose to pick that up from context?
>
> -T


Re: What is the syntax of a reference pointer in p6?

2018-10-07 Thread Brad Gilbert
Technically there is a way to reason about some Perl 6 features as pointers.

It would probably complicate it to view it this way though.

You can think about `is raw` as making it so that arguments are passed
by as bare "pointers".

sub foo ( $a is raw ) {
$a = 42;
}

my $b = 0;
foo( $b );
say $b; # 42

foo( 1 ) # error: Cannot assign to an immutable value

Note that even that isn't quite the same as pointers in other languages.

You can also check what type of thing it points to

sub bar ( $a is raw ) {
if $a.VAR.WHAT =:= Scalar {
$a = 42; # only change it if it is changeable
}
}

`is rw` is very similar to `is raw`, except it only accepts things
that can change.

---

Note that the default read only "view" of the arguments can also be
thought of as passing a pointer.

It's just a pointer that you can't do pointery things to.

So it doesn't (really) make a performance difference to use `is rw` or `is raw`.

(Technically there is a tiny speed-up to using `is raw`, but it should
go away once the code gets JITted.
So don't use `is raw` to get a performance boost.)
On Sat, Oct 6, 2018 at 5:16 AM ToddAndMargo via perl6-users
 wrote:
>
> On 10/6/18 2:01 AM, JJ Merelo wrote:
> > I don't know exactly what you mean by a reference pointer. If you mean a
> > pointer, there's no such thing as a pointer, although there is some way
> > to represent pointers in the NativeCall interface (which is properly
> > Rakudo) https://docs.perl6.org/language/traits#index-entry-CPointer.
> > There are no references either, as such. You can bind a variable to
> > another, but there's no special syntax for that.
> >
> > --
> > JJ
>
> Hi JJ,
>
> This is what they look like in Perl 5:
>
> sub GetOldRev ( $$ ) {
># Incomming:
>my $Extension= $_[1];
>my $WorkingDirectory = $_[2];
>my $CallingFunction  = $_[3];
>
># Outgoing.  Note: these are reference pointers to
>#  the calling variables
>#  do not pass constants ("") to them
>
>my $BaseTagPtr = \$_[0];
>my $OldRevPtr  = \$_[4];  $$OldRevPtr = -;
>my $OldFileNamePtr = \$_[5];  $$OldFileNamePtr = "";
>
> I will be happy if I never have to see a Reference Pointer ever again.
>
> -T


Re: Grammar doesn't seem to match any token

2018-09-24 Thread Brad Gilbert
I recommend to default to using `token` rather than `rule` or `regex`.

If you need backtracking, use `regex`

If you have a lot of parts that match whitespace use `rule` (generally
used for combining other tokens.)
On Sun, Sep 23, 2018 at 7:13 PM Patrick R. Michaud  wrote:
>
> I suspect the rule:
>
> rule other { .  }
>
> means that in
>
> $input = '~i << my $w = Weaver.new();
> Weave.parse($input, :actions($w));
>
> the "other" rule cannot match the "Y" or the "Z" because there would need to 
> be a space between them.  The use of "rule" as a regex declarator implies 
> that spaces in the regex source are :sigspace, which means that whitespace in 
> the rule prevents two word characters from being adjacent at that point and 
> any available whitespace is consumed.
>
> Change "rule" to "token" on these rules and I suspect you'll get  to 
> match (although  will also end up matching the space after the "i" in 
> the text string, since white spaces are no longer significant).  Or try just 
> changing the  rule to be a token and leave the others as rules.
>
> Phrased another way, the  rule as written now is roughly equivalent to 
> writing
>
>token other { .  \s* }
>
> which will match a word character only when it's not immediately followed by 
> another word character.
>
> Pm
>
>
> On Sun, Sep 23, 2018 at 08:01:31PM -0400, yary wrote:
> > Let's see.
> >
> > If you have my $input = '~i o<<<', then  matches.
> >
> >  'rule' turns on :sigspace. If you use 'token' instead of 'rule' then
> >  matches.
> >
> > I don't quite have the full picture of what's happening.
> >
> > -y
> >
> > On Sun, Sep 23, 2018 at 7:07 PM, Mark Carter  wrote:
> >
> > > My grammar doesn't seem to match the 'other' rule. What's wrong with it?
> > >
> > > grammar Weave {
> > > token TOP {   * }
> > > rule el {   |  |   }
> > > rule lt { '<'  }
> > > rule tilde { '~' \S+ }
> > > rule other { .  }
> > > }
> > >
> > > class Weaver {
> > > has Str $.outstr;
> > >
> > > method TOP   ($/) { make $ ; put("top called") ; put($) }
> > > method el($/) { put($/) }
> > > method tilde ($/) { say 'tilde called' }
> > > method lt($/) { make '' ; put(''); $!outstr ~= 'X' }
> > > method other ($/) { $!outstr ~= '.'; say 'other called'; put('.');
> > > }
> > >
> > > }
> > >
> > > $input = '~i << > > my $w = Weaver.new();
> > > Weave.parse($input, :actions($w));
> > > say $w.outstr; # outputs XXX
> > >
> > > It never once says 'other called'. It seems to be matching the '<' signs
> > > OK, and I think the '~' is OK, too. It's just any other token that it's 
> > > not
> > > matching.
> > >


Re: Could this be any more obscure?

2018-09-26 Thread Brad Gilbert
`$limit` isn't an array index.

It's an argument that is passed on to the Iterator that tells it to stop
when it has produced that many values.

(Also it returns a `Seq`, not a `Positional` [fixed])

You can think of it as the following:

'abc def'.words.head( $limit );

`words` does something more like this though:

sub words ( Str:D $input, $limit = Inf --> Seq ) {
gather {
my $count = 0;
my $prev-ws = -1;

loop {
# stop if $limit has been reached
last if ++$count > $limit;  #<--- $limit

# index of whitespace
my $next-ws = $input.index( ' ', $prev-ws + 1 );

# run after each iteration
NEXT $prev-ws = $next-ws;

with $next-ws {  # index found a space

# skip two whitespaces in a row
next if $prev-ws+1 == $next-ws;

# give the next value
take substr( $input, $prev-ws+1, $next-ws - $prev-ws - 1 );

} else { # index didn't find a space

# stop if the last character was a space
last if $prev-ws+1 >= $input.chars;

# give the last value
take substr( $input, $prev-ws+1 );

# end of sequence
last;
}
}
}
}

say words('abc def ghi jkl mno pqr stu vwx yz', 3).perl;
# ("abc", "def", "ghi").Seq
On Wed, Sep 26, 2018 at 1:57 AM Todd Chester  wrote:
>
> Hi All,
>
> Over on
>  https://docs.perl6.org/routine/words
> I see
>
> multi method words(Str:D $input: $limit = Inf --> Positional)
>
> HOW IN THE WORLD did they convert `$limit = Inf` into an
> array index!?!?!
>
> https://docs.perl6.org/type/Num#Inf
> And `Inf` means a number larger than Perl can handle or Infinity.
> What does that have to do with ANYTHING!?
>
> Yours in confusion,
> -T
>
> And the worst part is that I know how to use "words" and use it
> frequently.  And the documentation is a nightmare to understand.
>
> Link to Positional:
> https://docs.perl6.org/type/Positional
> Role for objects which support indexing them using
> postcircumfix:«[ ]» (usually list-like objects).
> Example types with Positional role include List,
> Array, Range, and Buf.
>
> I like him using `Str:D $input:` rather than just `Str:D:`
> and it is more intuitive


Re: More efficient of two coding styles?

2018-11-16 Thread Brad Gilbert
I don't know if either one has had any specific optimizations applied to it.

I would go for the multi-dispatch form if there is no overlap of functionality.
I think this would have a higher likelihood of getting the subroutine
inlined, because the code will be smaller.

If you really care that much more about performance than code
readability, then you should benchmark both.
You should run the benchmark on every release as it may change with
new optimizations.

I would personally just go with whatever is easier to understand.
On Thu, Nov 15, 2018 at 9:55 PM Richard Hainsworth
 wrote:
>
> Suppose I have a sub called C that runs different code depending
> on the content of an argument.
>
> There are two styles in Perl 6 to code this and my question is whether
> one is more efficient (speed/memory) than the other.
>
> In this example, one relies on multiple dispatch, while the other an
> explicit control statement.
>
> Putting aside clarity considerations, is there any performance reason to
> prefer one style over another?
>
> Style 1
>
> multi sub handle( $node WHERE *.name ~~ 'one' ) {
>
>  'this is a wonderful sub'
>
> }
>
> multi sub handle( $node WHERE *.name ~~ 'two' ) {
>
> 'twas brillig and the slivy toves did gyre'
>
> }
>
>
> Style 2
>
> sub handle ( $node ) {
>
>  given $node.name {
>
>  when 'one' { 'this is a wonderful sub' }
>
>  when 'two' { 'twas brillig and the slivy toves did gyre' }
>
>  }
>
> }


Re: Bad syntax check

2019-01-02 Thread Brad Gilbert
You can only list one type as a return type.

If there were a hypothetical Tuple type:

sub AddThree( Int $a, Int $b, Int $c --> Tuple[Str, Int] {
my Int $d = $a + $b + $c;
return Tuple[Str,Int].new( "a+b+c=", $d );
}


my Int $X = 0;
my Int $Y = 0;
my Str $Z;

Tuple[Str,Int].new( $X, $Y, $Y ) = AddThree( 1, 2, 3 );
say "X = <$X>\tY = <$Y>\tZ = <$Z>";

 There could be a circumfix operator to generate the Tuple objects.

You are dealing with Lists, which don't have a type specifier for their
elements.

On Wed, Jan 2, 2019 at 4:51 PM ToddAndMargo via perl6-users <
perl6-users@perl.org> wrote:

> On 1/2/19 2:27 PM, ToddAndMargo via perl6-users wrote:
> > On 1/2/19 2:11 PM, Simon Proctor wrote:
> >> Have you tried defining your return values in the signature?
> >>
> >> sub AddThree( Int $a, Int $b, Int $c --> Int) {...}
> >>
> >> With this the compiler knows what your function is supposed to return
> >> and can earn you in advance.
> >
> > I did and it blew up in my face so I stopped doing it.
>
> For example:
>
> $ cat RtnBooBoo2.pl6
> #!/usr/bin/env perl6
>
> sub AddThree( Int $a, Int $b, Int $c --> Str, Int ) {
> my Int $d = $a + $b + $c;
> return ( "a+b+c=", $d );
> }
>
> my Int $X = 0;
> my Int $Y = 0;
> my Str $Z;
>
> ( $X, $Y, $Y ) = AddThree( 1, 2, 3 );
> say "X = <$X>\tY = <$Y>\tZ = <$Z>";
>
>
>
> RtnBooBoo2.pl6
> ===SORRY!=== Error while compiling /home/linuxutil/./RtnBooBoo2.pl6
> Malformed return value (return constraints only allowed at the end of
> the signature)
> at /home/linuxutil/./RtnBooBoo2.pl6:3
> --> AddThree( Int $a, Int $b, Int $c --> Str⏏, Int ) {
>


Re: **@args question

2019-01-03 Thread Brad Gilbert
On Thu, Jan 3, 2019 at 12:43 AM ToddAndMargo via perl6-users
 wrote:
>
> On 1/2/19 10:17 PM, ToddAndMargo via perl6-users wrote:
> >  > On Wed, Jan 2, 2019 at 8:41 PM ToddAndMargo via perl6-users
> >  >  wrote:
> >  >>
> >  >> Hi All,
> >  >>
> >  >> Looking at
> >  >>
> >  >>  https://docs.perl6.org/routine/print
> >  >>
> >  >> I see
> >  >>
> >  >>  multi sub print(**@args --> True)
> >  >>
> >  >> Question.  If I wanted to create my own print routine
> >  >> using **@args, how would I declare it?
> >  >>
> >  >>  sub printx( **@args data ) {...}
> >  >>
> >  >>
> >  >> Many thanks,
> >  >> -T
> >
> >
> > On 1/2/19 10:06 PM, Brad Gilbert wrote:
> >> The variable name in :(**@args) is @args, it could be any valid array
> >> identifier like @data
> >>
> >>  sub printx( **@data ){…}
> >>
> >> Note that there are several forms for slurpy positional arguments.
> >>
> >>  :(   @a ) # not slurpy at all, takes one Positional argument and
> >> aliases it as @a.
> >>
> >>  :(  *@a ) # flattening slurpy  (1,),2,3 → 1,2,3 and ((1,),2,3) →
> >> 1,2,3
> >>  :( **@a ) # structured slurpy (1,),2,3 → (1,),2,3 and ((1,),2,3) →
> >> ((1,),2,3) # note there is no change
> >>  :(  +@a ) # one-arg rule slurpy (1,),2,3 → (1,),2,3 and ((1,),2,3)
> >> → (1,),2,3 # note that the second one changes
> >>
> >> Note that itemized values do not get flattened for :(*@a), and that
> >> Array values are itemized.
> >>
> >> I like to consider the one-arg rule slurpy :(+@a) to be like a
> >> combination between non-slurpy :(@a) and structured slurpy :(**@a)
> >> That is a one-arg rule slurpy will sometimes be like an alias to a
> >> singular positional, otherwise it will act like a structured slurpy.
> >>
> >> Note that all but the [aliasing] non-slurpy :(@a) are [almost] always
> >> Array's.
> >>
> >> ---
> >>
> >> The one-arg rule slurpy is the oddest one of the bunch so here is some
> >> brief information:
> >>
> >> The one-arg rule slurpy can be sigiless :(+a), in which case it will
> >> be a List instead of an Array or an alias to the single argument
> >> depending on what it was.
> >>
> >>  sub one-arg-rule ( +args ){
> >>  say args.^name, " # ", args.perl;
> >>  }
> >>
> >>  one-arg-rule(  (1,),2,3  ); # List # ((1,), 2, 3)
> >>  one-arg-rule( ((1,),2,3) ); # List # ((1,), 2, 3) # one-arg rule
> >>  one-arg-rule( ((1,),2,3).Seq ); # Seq # ((1,), 2, 3).Seq #
> >> one-arg rule
> >>  one-arg-rule(  1..3   ); # List # (1, 2, 3)
> >>  one-arg-rule( (1..3,) ); # List # (1..3,)
> >>
> >>  sub one-arg-Array ( +@args ){
> >>  say @args.^name, " # ", @args.perl;
> >>  }
> >>
> >>  one-arg-Array(  (1,),2,3  ); # Array # [(1,), 2, 3]
> >>  one-arg-Array( ((1,),2,3) ); # Array # [(1,), 2, 3]
> >>  one-arg-Array( ((1,),2,3).Seq ); # List # ((1,), 2, 3)
> >>  one-arg-Array(  1..3   ); # Array # [1, 2, 3]
> >>  one-arg-Array( (1..3,) ); # Array # [1..3,]
> >>
> >> The one-arg rule exists because people tend to write the following:
> >>
> >>  my @a = [1,2,3];
> >>
> >> When the correct way to write it is:
> >>
> >>  my @a = 1,2,3;
> >>
> >> There are various other places where the one-arg rule is also used, so
> >> it was made available to everyone.
> >>
> >> ---
> >>
> >> Don't get too flustered if you don't understand all of the nuances, it
> >> take everybody a while to understand them.
> >>
> >
> > Thank you!
> >
> > The term "slurpy" did help a lot.
> >
> > :-)
> >
> > I am writing your explanation down for my records.
>
>
> Well Golly!
>
> $ p6 'sub printx(**@args){print(@args)}; printx("abc",1,"def\n");'
> abc 1 def
>
> $ p6 'sub printx(**@args){print @args, "\n"}; printx("abc",1,"def");'
> abc 1 def
>
> Question:
> $ p6 'sub printx(**@args){print(@args)}; printx("abc","xyz","def\n");'
> abc xyz def
>
> Are the spaces suppose to be there?

The spaces are there because you are passing `@args` to `print` as a
single value.
`print` coerces all its values to `Str` before printing, and an Array
adds spaces between elements when turned into a Str.

Simple fix use `|@args` to Slip it into the call to `print`

$ p6 'sub printx(**@args){print( |@args, "\n" )};
printx("abc","xyz","def");'
abcxyzdef


Re: **@args question

2019-01-02 Thread Brad Gilbert
The variable name in :(**@args) is @args, it could be any valid array
identifier like @data

sub printx( **@data ){…}

Note that there are several forms for slurpy positional arguments.

:(   @a ) # not slurpy at all, takes one Positional argument and
aliases it as @a.

:(  *@a ) # flattening slurpy  (1,),2,3 → 1,2,3 and ((1,),2,3) → 1,2,3
:( **@a ) # structured slurpy (1,),2,3 → (1,),2,3 and ((1,),2,3) →
((1,),2,3) # note there is no change
:(  +@a ) # one-arg rule slurpy (1,),2,3 → (1,),2,3 and ((1,),2,3)
→ (1,),2,3 # note that the second one changes

Note that itemized values do not get flattened for :(*@a), and that
Array values are itemized.

I like to consider the one-arg rule slurpy :(+@a) to be like a
combination between non-slurpy :(@a) and structured slurpy :(**@a)
That is a one-arg rule slurpy will sometimes be like an alias to a
singular positional, otherwise it will act like a structured slurpy.

Note that all but the [aliasing] non-slurpy :(@a) are [almost] always Array's.

---

The one-arg rule slurpy is the oddest one of the bunch so here is some
brief information:

The one-arg rule slurpy can be sigiless :(+a), in which case it will
be a List instead of an Array or an alias to the single argument
depending on what it was.

sub one-arg-rule ( +args ){
say args.^name, " # ", args.perl;
}

one-arg-rule(  (1,),2,3  ); # List # ((1,), 2, 3)
one-arg-rule( ((1,),2,3) ); # List # ((1,), 2, 3) # one-arg rule
one-arg-rule( ((1,),2,3).Seq ); # Seq # ((1,), 2, 3).Seq # one-arg rule
one-arg-rule(  1..3   ); # List # (1, 2, 3)
one-arg-rule( (1..3,) ); # List # (1..3,)

sub one-arg-Array ( +@args ){
say @args.^name, " # ", @args.perl;
}

one-arg-Array(  (1,),2,3  ); # Array # [(1,), 2, 3]
one-arg-Array( ((1,),2,3) ); # Array # [(1,), 2, 3]
one-arg-Array( ((1,),2,3).Seq ); # List # ((1,), 2, 3)
one-arg-Array(  1..3   ); # Array # [1, 2, 3]
one-arg-Array( (1..3,) ); # Array # [1..3,]

The one-arg rule exists because people tend to write the following:

my @a = [1,2,3];

When the correct way to write it is:

my @a = 1,2,3;

There are various other places where the one-arg rule is also used, so
it was made available to everyone.

---

Don't get too flustered if you don't understand all of the nuances, it
take everybody a while to understand them.

On Wed, Jan 2, 2019 at 8:41 PM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> Looking at
>
> https://docs.perl6.org/routine/print
>
> I see
>
> multi sub print(**@args --> True)
>
> Question.  If I wanted to create my own print routine
> using **@args, how would I declare it?
>
> sub printx( **@args data ) {...}
>
>
> Many thanks,
> -T
>
>
> --
> ~~
> When you say, "I wrote a program that
> crashed Windows," people just stare at
> you blankly and say, "Hey, I got those
> with the system, for free."
>   -- Linus Torvalds
> ~~


Re: I need m/ help

2019-01-14 Thread Brad Gilbert
Nl is not “*non-arabic numbers*” and it is not “*numbers that have a value
by themselves*”.
While both seem like correct statements, they are the wrong way to think
about the Nl category.
If either were entirely correct then there wouldn't be a need for No
(Number other).

*Nl (Number letter)* is for *“Numerals composed of letters or letterlike
symbols (e.g., Roman numerals)”*
(copied from
https://en.wikipedia.org/wiki/Template:General_Category_(Unicode) )

Note that Roman numerals also “*have a positional value*” and can “*be
collated to other numbers to form bigger numbers*”.


On Mon, Jan 14, 2019 at 12:29 AM JJ Merelo  wrote:

> I would say they are numbers that have a value by themselves, but can't be
> collated to other numbers to form bigger numbers, that is, they are not
> digits and they don't have a positional value.
>
> El dom., 13 ene. 2019 a las 20:13, Timo Paulssen ()
> escribió:
>
>> There ought to be some documentation on the unicode website or maybe the
>> wikipedia article has some explanation.
>>
>> Other than that, here's a list of all unicode characters that match <:Nl>:
>>
>> perl6 -e 'for ^0x10 { say "$_: $(chr($_)) $(uniname($_))" if chr($_)
>> ~~ /<:Nl>/ }'
>>
>> 5870: ᛮ RUNIC ARLAUG SYMBOL
>> 5871: ᛯ RUNIC TVIMADUR SYMBOL
>> 5872: ᛰ RUNIC BELGTHOR SYMBOL
>> 8544: Ⅰ ROMAN NUMERAL ONE
>> 8545: Ⅱ ROMAN NUMERAL TWO
>> 8546: Ⅲ ROMAN NUMERAL THREE
>> 8547: Ⅳ ROMAN NUMERAL FOUR
>> 8548: Ⅴ ROMAN NUMERAL FIVE
>> 8549: Ⅵ ROMAN NUMERAL SIX
>> 8550: Ⅶ ROMAN NUMERAL SEVEN
>> 8551: Ⅷ ROMAN NUMERAL EIGHT
>> 8552: Ⅸ ROMAN NUMERAL NINE
>> 8553: Ⅹ ROMAN NUMERAL TEN
>> 8554: Ⅺ ROMAN NUMERAL ELEVEN
>> 8555: Ⅻ ROMAN NUMERAL TWELVE
>> 8556: Ⅼ ROMAN NUMERAL FIFTY
>> 8557: Ⅽ ROMAN NUMERAL ONE HUNDRED
>> 8558: Ⅾ ROMAN NUMERAL FIVE HUNDRED
>> 8559: Ⅿ ROMAN NUMERAL ONE THOUSAND
>> 8560: ⅰ SMALL ROMAN NUMERAL ONE
>> 8561: ⅱ SMALL ROMAN NUMERAL TWO
>> 8562: ⅲ SMALL ROMAN NUMERAL THREE
>> 8563: ⅳ SMALL ROMAN NUMERAL FOUR
>> 8564: ⅴ SMALL ROMAN NUMERAL FIVE
>> 8565: ⅵ SMALL ROMAN NUMERAL SIX
>> 8566: ⅶ SMALL ROMAN NUMERAL SEVEN
>> 8567: ⅷ SMALL ROMAN NUMERAL EIGHT
>> 8568: ⅸ SMALL ROMAN NUMERAL NINE
>> 8569: ⅹ SMALL ROMAN NUMERAL TEN
>> 8570: ⅺ SMALL ROMAN NUMERAL ELEVEN
>> 8571: ⅻ SMALL ROMAN NUMERAL TWELVE
>> 8572: ⅼ SMALL ROMAN NUMERAL FIFTY
>> 8573: ⅽ SMALL ROMAN NUMERAL ONE HUNDRED
>> 8574: ⅾ SMALL ROMAN NUMERAL FIVE HUNDRED
>> 8575: ⅿ SMALL ROMAN NUMERAL ONE THOUSAND
>> 8576: ↀ ROMAN NUMERAL ONE THOUSAND C D
>> 8577: ↁ ROMAN NUMERAL FIVE THOUSAND
>> 8578: ↂ ROMAN NUMERAL TEN THOUSAND
>> 8581: ↅ ROMAN NUMERAL SIX LATE FORM
>> 8582: ↆ ROMAN NUMERAL FIFTY EARLY FORM
>> 8583: ↇ ROMAN NUMERAL FIFTY THOUSAND
>> 8584: ↈ ROMAN NUMERAL ONE HUNDRED THOUSAND
>> 12295: 〇 IDEOGRAPHIC NUMBER ZERO
>> 12321: 〡 HANGZHOU NUMERAL ONE
>> 12322: 〢 HANGZHOU NUMERAL TWO
>> 12323: 〣 HANGZHOU NUMERAL THREE
>> 12324: 〤 HANGZHOU NUMERAL FOUR
>> 12325: 〥 HANGZHOU NUMERAL FIVE
>> 12326: 〦 HANGZHOU NUMERAL SIX
>> 12327: 〧 HANGZHOU NUMERAL SEVEN
>> 12328: 〨 HANGZHOU NUMERAL EIGHT
>> 12329: 〩 HANGZHOU NUMERAL NINE
>> 12344: 〸 HANGZHOU NUMERAL TEN
>> 12345: 〹 HANGZHOU NUMERAL TWENTY
>> 12346: 〺 HANGZHOU NUMERAL THIRTY
>> 42726: ꛦ BAMUM LETTER MO
>> 42727: ꛧ BAMUM LETTER MBAA
>> 42728: ꛨ BAMUM LETTER TET
>> 42729: ꛩ BAMUM LETTER KPA
>> 42730: ꛪ BAMUM LETTER TEN
>> 42731: ꛫ BAMUM LETTER NTUU
>> 42732: ꛬ BAMUM LETTER SAMBA
>> 42733: ꛭ BAMUM LETTER FAAMAE
>> 42734: ꛮ BAMUM LETTER KOVUU
>> 42735: ꛯ BAMUM LETTER KOGHOM
>> 65856: ŀ GREEK ACROPHONIC ATTIC ONE QUARTER
>> 65857: Ł GREEK ACROPHONIC ATTIC ONE HALF
>> 65858: ł GREEK ACROPHONIC ATTIC ONE DRACHMA
>> 65859: Ń GREEK ACROPHONIC ATTIC FIVE
>> 65860: ń GREEK ACROPHONIC ATTIC FIFTY
>> 65861: Ņ GREEK ACROPHONIC ATTIC FIVE HUNDRED
>> 65862: ņ GREEK ACROPHONIC ATTIC FIVE THOUSAND
>> 65863: Ň GREEK ACROPHONIC ATTIC FIFTY THOUSAND
>> 65864: ň GREEK ACROPHONIC ATTIC FIVE TALENTS
>> 65865: ʼn GREEK ACROPHONIC ATTIC TEN TALENTS
>> 65866: Ŋ GREEK ACROPHONIC ATTIC FIFTY TALENTS
>> 65867: ŋ GREEK ACROPHONIC ATTIC ONE HUNDRED TALENTS
>> 65868: Ō GREEK ACROPHONIC ATTIC FIVE HUNDRED TALENTS
>> 65869: ō GREEK ACROPHONIC ATTIC ONE THOUSAND TALENTS
>> 65870: Ŏ GREEK ACROPHONIC ATTIC FIVE THOUSAND TALENTS
>> 65871: ŏ GREEK ACROPHONIC ATTIC FIVE STATERS
>> 65872: Ő GREEK ACROPHONIC ATTIC TEN STATERS
>> 65873: ő GREEK ACROPHONIC ATTIC FIFTY STATERS
>> 65874: ΠGREEK ACROPHONIC ATTIC ONE HUNDRED STATERS
>> 65875: œ GREEK ACROPHONIC ATTIC FIVE HUNDRED STATERS
>> 65876: Ŕ GREEK ACROPHONIC ATTIC ONE THOUSAND STATERS
>> 65877: ŕ GREEK ACROPHONIC ATTIC TEN THOUSAND STATERS
>> 65878: Ŗ GREEK ACROPHONIC ATTIC FIFTY THOUSAND STATERS
>> 65879: ŗ GREEK ACROPHONIC ATTIC TEN MNAS
>> 65880: Ř GREEK ACROPHONIC HERAEUM ONE PLETHRON
>> 65881: ř GREEK ACROPHONIC THESPIAN ONE
>> 65882: Ś GREEK ACROPHONIC HERMIONIAN ONE
>> 65883: ś GREEK ACROPHONIC EPIDAUREAN TWO
>> 65884: Ŝ GREEK ACROPHONIC THESPIAN TWO
>> 65885: ŝ GREEK ACROPHONIC CYRENAIC TWO DRACHMAS
>> 65886: Ş GREEK ACROPHONIC EPIDAUREAN TWO DRACHMAS
>> 65887: ş GREEK 

Re: I need m/ help

2019-01-14 Thread Brad Gilbert
That is only because the special coding rules for Roman numerals weren't added.

It still is a wrong way to think about Nl.

On Mon, Jan 14, 2019 at 12:59 PM JJ Merelo  wrote:
>
>
>
> El lun., 14 ene. 2019 a las 18:41, Brad Gilbert () 
> escribió:
>>
>> Nl is not “non-arabic numbers” and it is not “numbers that have a value by 
>> themselves”.
>> While both seem like correct statements, they are the wrong way to think 
>> about the Nl category.
>> If either were entirely correct then there wouldn't be a need for No (Number 
>> other).
>>
>> Nl (Number letter) is for “Numerals composed of letters or letterlike 
>> symbols (e.g., Roman numerals)”
>> (copied from 
>> https://en.wikipedia.org/wiki/Template:General_Category_(Unicode) )
>>
>> Note that Roman numerals also “have a positional value” and can “be collated 
>> to other numbers to form bigger numbers”.
>
>
> No, they don't, at least not in Perl 6:
>
> say ⅮⅭ
> https://gist.github.com/Whateverable/14d4c361c81bc6e784c42a12ca83a6a0
>
> You can try for any other Nl, it just does not. However:
>
> say Ⅾ+Ⅽ; OUTPUT: «600␤»
>
> (because they have a numeric value by themselves).
>
> Only those with the Nd property can be collated to form any kind of number; 
> these are in number system which are positional and decimal (at least those 
> I've tried):
>
> say ߁߃ # OUTPUT: «13␤»
>
> (these are Nko digits)
>
> Cheers
>
> JJ


Re: say Cool-concat-junction question

2018-12-23 Thread Brad Gilbert
I am sure about that

:<~>.cando(\(3,('a'|'b'))».signature.say
# ((*@args --> Str:D))
:<~>.cando(\('x',('a'|'b')))».signature.say
# ((Str:D $a, Junction:D $b) (*@args --> Str:D))

Since there is a Junction candidate (or rather three), there is
probably a reason for it.

Also if you turn the 3 into a Junction it also starts to work

any(3) ~ ('a'|'b')
# any(3a, 3b)

On Sun, Dec 23, 2018 at 2:22 AM JJ Merelo  wrote:
>
>
>
> El dom., 23 dic. 2018 a las 7:39, Brad Gilbert () escribió:
>>
>> I turns out there is a candidate for
>>
>> Str:D, Junction:D
>>
>> but not for
>>
>> Any:D, Junction:D
>>
>> so it is going through one of the other :<~> candidates,
>> specifically it looks like it could be
>>
>> *@args
>>
>> Which doesn't apparently work with Junctions. So yes it is a bug.
>
>
> Um, not sure about that. One might expect a distributive property of the kind 
> a ~ f(b,c) would do something like f(a~b, a~c), but this does not need to 
> apply in this case, maybe because in this particular Any case a~b and the 
> rest would work, but not in general (because there might not be a sensible 
> stringification of a). This works, for instance: say '3' ~ (3|'4')
> If you think it's a bug, or simply inconsistent behavior, you could file an 
> issue, anyway. But I'm not so sure in this case.
>
> Cheers
>
> JJ


Re: say Cool-concat-junction question

2018-12-22 Thread Brad Gilbert
I turns out there is a candidate for

Str:D, Junction:D

but not for

Any:D, Junction:D

so it is going through one of the other :<~> candidates,
specifically it looks like it could be

*@args

Which doesn't apparently work with Junctions. So yes it is a bug.

On Sat, Dec 22, 2018 at 9:05 PM yary  wrote:
>
> What's going on here- is this error a mistake on my part, or a bug?
>
> $ perl6 -e "say 3 ~ ( 'a' | 'b' )"
>
> Type check failed for return value; expected Str:D but got Junction 
> (any("3a", "3b"))
>
>   in block  at -e line 1
>
>
> $ perl6 -e "say 'x' ~ ( 'a' | 'b' )"
>
> any(xa, xb)
>
>
> $ perl6 -v
>
> This is Rakudo Star version 2018.10 built on MoarVM version 2018.10
>
> implementing Perl 6.c.
>
>
>
> -y


Re: so as a method: Is this expected or a bug?

2018-12-21 Thread Brad Gilbert
You got the order of operations wrong.

Method calls happen before prefix operators

These are identical

+@a.so
+(@a.so)
@a.so.Numeric
@a.Bool.Numeric
+?@a

As are these

+«@a».so
+«(@a».so)
@a».so».Numeric
@a».Bool».Numeric
+«?«@a

Postfix operators also happen before prefix operators generally
(depends on precedence)

?$a++
?($a++)

---

This leads me to question why you used the `+` prefix operator at all?
It could only ever be slower (or more wrong) than just using `.so`
`.Bool` or prefix `?`

`.so` only has to check to see if the array is longer than zero elements.

By converting it to Numeric it would have to count all of the values first.
(I don't think it actually works like this)

If it is declared with a lazy list it will throw an error.

 my @a = 1,1, *+* ... *;

 +@a; # Failure: Cannot .elems a lazy list

 ?@a; # True

 ?+@a; # False

That is False because a Failure is always False.

On Fri, Dec 21, 2018 at 2:28 AM Richard Hainsworth
 wrote:
>
> A snippet:
>
>  my @a = 1..10;
>  put +@a.so; # output 1
>  put so(+@a); # output True
>  put (+@a).so; # output True
>
> This caught me because I used +@s.so when I tried to do something like:
>
>  # in a class with 'has Bool $.pass;'
>  return unless ( $!pass = +@a.so );
>  # fails with a Type mismatch of Int being assigned to Bool
>
> Is this an expected result, or a bug?
>
>
> (I was going to ask this on StackOverflow, but it seems so like a bug
> that I decided to ask here first)


Re: How to use sub/method 'dir'

2018-11-25 Thread Brad Gilbert
The reason `dir('a', test => { .IO.d })` doesn't work like you expect
is that it is passed strings.

> dir('a', test => {.say});
.
c
b
..
("a/.".IO "a/c".IO "a/b".IO "a/..".IO)

So `.IO.d` is looking to see if the CWD directory had a directory of
that name, not the `a` directory.

To get it to work append the `a`

> dir('a', test => { "a/$_".IO.d })
("a/.".IO "a/b".IO "a/..".IO)

---

I would argue that inside of the `test` that `$*CWD` should be set to
`a`, and/or the values should be IO objects.
(They are going to become IO objects eventually anyway.)
This would make it so your code would just work.

sub dir ( $path, : ){
my @paths = ::dir($path);

indir $path, { # set $*CWD

my @results = @paths.grep: {
test( $_.IO ) # use IO object, not Str
}
}
@results
}
On Sat, Nov 24, 2018 at 3:19 PM Fernando Santagata
 wrote:
>
> Hello,
>
> I think that I don't understand how the 'test' argument of 'dir' works.
> I have a directory 'a', which contains a subdirectory 'b' and a file 'c'; I 
> want to select only the subdirectories of 'a'.
>
> Using the REPL I tried to ask the content of the directory 'a':
>
> > my @dirs = dir('a')
> ["a/c".IO "a/b".IO]
> > my @dirs = dir('a', test => { .IO.d })
> ["a/.".IO "a/..".IO]
> Why omitting the test the code returns the right list, while adding the test 
> it returns just '.' and '..'?
>
> If I do the same thing for the top level directory '.' the behavior is 
> different:
>
> > my @dirs = dir('.', test => { .IO.d })
> [".".IO "a".IO "..".IO]
>
> Now I can see the directory 'a'.
> If I descend a level, doing a 'cd a', the behavior is consistent with what I 
> see at the previous level.
> I'm confused.
>
> I'm using version 2018.10.
>
> --
> Fernando Santagata


Re: How to use sub/method 'dir'

2018-11-27 Thread Brad Gilbert
On Mon, Nov 26, 2018 at 6:26 PM Trey Harris  wrote:
>
>
>
> On Mon, Nov 26, 2018 at 04:56 Fernando Santagata  
> wrote:
>>
>> On Sun, Nov 25, 2018 at 5:34 PM Brad Gilbert  wrote:
>>>
>>> The reason `dir('a', test => { .IO.d })` doesn't work like you expect
>>> is that it is passed strings.
>>
>>
>> Thank you!
>> I could have inferred that from the declaration of the 'test' argument here 
>> https://docs.perl6.org/routine/dir where the test is being done against '.' 
>> and '..', two strings:
>>
>>> subdir(Cool $path = '.', Mu :$test = none('.', '..'))
>>> method dir(IO::Path:D: Mu :$test = none('.', '..'))
>>
>>
>> but I guess it's a long stretch.
>> Maybe a note in the docs would be useful to others.
>>
>>>
>>> I would argue that inside of the `test` that `$*CWD` should be set to
>>> `a`, and/or the values should be IO objects.
>>> (They are going to become IO objects eventually anyway.)
>>
>>
>> Indeed I think that even tough one can do any kind of test on the 
>> directory's content, the most usual ones are those using the file test 
>> operators, so defaulting to IO is probably more useful than defaulting to 
>> Str.
>
>
> I'm not sure that's true. I think it's a question of following the Principle 
> of Least Surprise.

Exactly, the way it works right now is surprising (to new Perl 6 programmers).

It even took me a few seconds to realize what the problem was, and
I've been learning Perl 6 for about a decade.

> The only substantive difference between `my $i = "foobar".IO` and `my $s = 
> "foobar"` besides needing to stick the `.IO` in when you want to do IO-y 
> things with `$s` is that `$i` retains the knowledge of $*CWD at the time of 
> instantiation. But `dir` always returns paths that stringify _relative to 
> `$*CWD` at the time of the `dir` call._ Notice the difference between 
> `$i.gist` (which, if evaluated, will not consistently re-create the original 
> object) and `$i.perl` (which will):
>
> > $f.gist
> "foobar".IO
> > $i.perl
> IO::Path.new("foobar", :SPEC(IO::Spec::Unix), 
> :CWD("/home/trey/perl6/rakudo-star"))
> > chdir "/tmp"
> "/tmp".IO
> > $f.gist
> "foobar".IO
> > $i.perl
> IO::Path.new("foobar", :SPEC(IO::Spec::Unix), 
> :CWD("/home/trey/perl6/rakudo-star"))
>
> The string, OTOH, is also relative to the `$*CWD` at the time of the `dir()` 
> call, but if you call `.IO` on it after changing directories, the path object 
> is interpreted relative to the new directory. This is unsurprising; what 
> _would be_ surprising is if a string changed as a result of external program 
> state.

I was only talking about the object within the `:test` argument of the
`dir` call.

The resulting sequence wouldn't change at all.

> Large-scale file-munging operations have always been squarely in Perl's 
> wheelhouse, and doing fancy operations with complex subtrees (such as 
> syncing, normalizing, archiving, collating, etc.) are common.

Precisely why I suggested changing it.
The way it works now is harder to use than it could be.

> The string doesn't offer as much in the way of features, but I think it 
> behaves much more predictably when doing these sorts of operations. If you 
> `chdir $dest` after the `dir` but before doing your munging, then you must 
> remember to prepend the old working directory if you need to access the 
> original file (i.e., `$src = $*CWD;  for @files -> $f { $src.add($f) ... }`), 
> while the new files would just be `$f`. If you don't change directories, then 
> you must say `$dest.add($f)` to refer to the new files, while the old file is 
> just `$f`. But in either case, it's unsurprising and predictable.

Actually Str behaves less predictably than an IO object for the `test` argument.
If you want to compare it stringwise, do so and it works:

my $dir = IO::Path( 'b', :CWD('a'.IO) );

say $dir eq 'b'; # True

If you want to see if it is a directory, just ask it:

say $dir.d; # True

`.gist` doesn't stringify an object, it returns enough information for
a human to be able to figure out what the object is.

When you do stringy operations on an IO::Path object (or any object),
it calls the `.Str` method not `.gist`.
The only things which implicitly call `.gist` is `say` and `note`.

Now what I proposed was having the CWD set to the directory being
examined inside of `test`, which is a different `CWD` than the result
of the `dir` call.

> say dir('a'):test( {temp $*CWD = 'a'.IO; .IO.d && .IO ~~ none(<. ..>)} )
("a/b".IO)
&g

Re: I need hash string help

2019-01-11 Thread Brad Gilbert
$a is short for $a{'a','b'}

This also happens in string literals

my $a = { a => 1, b => 2 };
say "$a"; # 1 2
say "$a{'a','b'}"; # 1 2

A simple way to stop this is to add a backslash

my $a = 'b'
say "$a\"; # b

You can also call methods on variables in string literals, as long as
you use parentheses.

my $a = Date.today;
say "$a.year()-$a.month()-$a.day()"; # 2019-1-11

(Note that Date has a .-mm-dd() method)

---

Looking at the message you just added:

Perl 6 has a Version type.

my $a = Version.new("12.3.4.1");
my $b = Version.new("111.3.4.1");

say $a before $b; # True

Also there is syntax for creating a Version literal

my $a = v12.3.4.1;
my $b = v111.3.4.1;

say $a before $b; # True

There are useful methods on Versions

my $a = v12.3.4.1;
say $a.parts.perl; # (12, 3, 4, 1)

On Fri, Jan 11, 2019 at 8:12 PM ToddAndMargo via perl6-users
 wrote:
>
> On 1/11/19 5:08 PM, ToddAndMargo via perl6-users wrote:
> > Hi All,
> >
> > Now what am I doing wrong?  I need to convert the value in a
> > hash to a string:
> >
> > $ p6 'my $x = "acme"; my Str $y; my %Vendors = ( acme => ContactName =>
> > "Larry" ); $y= %Vendors; say $y;'
> > Type check failed in assignment to $y; expected Str but got Any (Any)
> >in block  at -e line 1
> >
> >
> > $ p6 'my $x = "acme"; my Str $y; my %Vendors = ( acme => ContactName =>
> > "Larry" ); $y= %Vendors.Str; say $y;'
> > Use of uninitialized value of type Any in string context.
> > Methods .^name, .perl, .gist, or .say can be used to stringify it to
> > something meaningful.
> >in block  at -e line 1
> >
> >
> > Many thanks,
> > -T
>
> Figured out my booboo. I had to change from
>
> $PartsStr =
>"Hi $Manager," ~
>"Account Number: $AccountNo" ~
>
> to
>
> $PartsStr =
>"Hi " ~ $Manager ~ "," ~
>"Account Number: " ~ $AccountNo ~ "" ~


Re: I need m/ help

2019-01-13 Thread Brad Gilbert
<:Nl> matches a Number that is letter-like

I mean obviously `Ⅿ` (ROMAN NUMERAL ONE THOUSAND) looks like a letter.

There is also <:Nd> for Number digit,
and <:No> for other Numbers

If you want to find out the general category of a character you can
call `.uniprop`.

say "1".uniprop; # Nd # Number digit
say "Ⅿ".uniprop; # Nl # Number letter # (ROMAN NUMERAL ONE THOUSAND)
say "¼".uniprop; # No # Number other

say "m".uniprop; # Ll # Letter lowercase
say "M".uniprop; # Lu # Letter uppercase
say "ߢ".uniprop; # Lo # Letter other
say "ῼ".uniprop; # Lt # Letter titlecase
say "ʹ".uniprop; # Lm # Letter modifier # (MODIFIER LETTER PRIME)

say (0..0x10).map(*.uniprop).Set.keys.sort;
# (Cc Cf Cn Co Cs Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc Pd Pe Pf Pi
Po Ps Sc Sk Sm So Zl Zp Zs)

These are all defined by Unicode.

The MODIFIER LETTER PRIME is particularly useful if you want to write code like:

my \A = …;
my \Aʹ = A + …;

That works because it is a letter.

Note that if you call it on a number you are asking for the uniprop of
the character with that codepoint.

say "A".ord; # 65
say 65.uniprop; # Lu # because A is an uppercase Letter

There is also a `.uniprops` for getting a sequence of unicode
properties for each character in a string.

say "A5".uniprops; # (Lu Nd)
say "A5".comb.map(*.uniprop); # (Lu Nd)

On Sun, Jan 13, 2019 at 2:42 AM ToddAndMargo via perl6-users
 wrote:
>
> On 1/12/19 3:04 PM, Timo Paulssen wrote:
> > On 12/01/2019 23:40, ToddAndMargo via perl6-users wrote:
> >> But this does not.  What is wrong with (<:N>**2)  ?
> >>
> >> $ perl6 -e 'my Str $Date=DateTime.now.Str; $Date~~m/ (<:N>**4) "-"
> >> (<:N>**2) "-" (<:Nl>**2) "T" .* /; print "$Date\n\t$0  $1  $2\n"'
> >> Use of Nil in string context
> >>in block  at -e line 1
> >> Use of Nil in string context
> >>in block  at -e line 1
> >> Use of Nil in string context
> >>in block  at -e line 1
> >> 2019-01-12T14:33:10.692302-08:00
> >>
> >>
> >> Many thanks,
> >> -T
> >
> >
> > Hi Todd,
> >
> > it looks like you have an accidental l in there: the third capture group
> > has <:Nl> instead of <:N>.
> >
> > Changing that makes it work for me
> >- Timo
> >
>
> Hi Timo,
>
> Just out of curiosity, what is the difference between "Number (<:N>)"
> and "Number Like (<:Nl>)"?  What would they not be the same in this context?
>
> My latest:
>
> $ perl6 -e 'DateTime.now.Str ~~ m/ (<:N>+) "-" (<:N>+) "-" (<:N>+) "T"
> .* /; my Str $Po="$1$2x$0_"; $Po~~s/x20//;print "$Po\n";'
>
> 011319_
>
> I stuck the "x" in there so I would not clobber day = 20.
>
> -T


Re: A comparison between P5 docs and p6 docs

2018-09-12 Thread Brad Gilbert
The signatures in the docs are often the exact same signatures
as the code they are documenting.

> Str.^lookup('contains').candidates.map: *.signature.say
(Str:D: Cool:D $needle, *%_)
(Str:D: Str:D $needle, *%_)
(Str:D: Cool:D $needle, Cool:D $pos, *%_)
(Str:D: Str:D $needle, Int:D $pos, *%_)

So the name of the positional parameters tend to be whatever
the person who wrote the code decided to call them.
If you have a better idea, you could create an issue or pull-request.

---

The real problem is that someone has to be able to see it
from the beginner's perspective, but also has to know how
it actually works.
They also have to have the time and ambition to go through them.

If you create a detailed issue, or pull-request, at least people
will know where their work is needed.

---

There have been cases where documenting something
lead to the discovery of a bug in the implementation.
On Tue, Sep 11, 2018 at 7:05 PM ToddAndMargo  wrote:
>
> On 09/11/2018 08:17 AM, Laurent Rosenfeld via perl6-users wrote:
> > Hi Todd,
> >
> > I fully agree with Tom B.'s message that you should really set out to
> > read a Perl 6 book. Many of the things you asked are covered in most of
> > the available books. And the available books are easier than the
> > official documentation for a beginner to start understand the basic
> > underlying concepts.
> >
> > I should add that you don't even have to /buy/ one book, since my own
> > /Think Perl 6/ book is freely available on the Internet (Creative
> > Commons license): https://greenteapress.com/wp/think-perl-6/. Well, if
> > you are interested in reading it, I'd suggest you look for the PDF on my
> > Github repository
> > (https://github.com/LaurentRosenfeld/thinkperl6/tree/master/PDF),
> > because it is more up-to-date (number of small corrections made
> > following comments from readers).
> >
> > So it would take you just a few minutes (at no cost) to download it and
> > start enjoying it.
> >
> > Cheers,
> > Laurent.
>
>
> Hi Laurent,
>
> Ordinarily I would agree with you.  But I know my own brain and
> how it works.  I only learn by doing.  Have tried to change that
> and can't.
>
> When I "dive in", I open up the reference docs and bang away.
> I also use Google, but that is next to useless in Perl 6 as Perl 5
> hits drowned Perl 6 out.
>
> I am 62 years old, have a bachelors degree in Electronic and
> Computer Engineering, Cum Laude and have been programming
> things all my life.  I live with the reference page open
> while pounding out code.
>
> Perl 6's document are next to useless for me.  This is the first
> time I have come across references that were so badly done.
> And programming of the Automated Test Equipment I did
> had some documents to behold.  CP-M was not fun either.
>
> Do not misunderstand, I ADORE Perl 6.  It is a wonderful clean
> up of Perl 5, especially the subroutine definitions and regex's.
> The only step backward is the docs.
>
> The developers have their own specification/documentation.
> The reference docs need to be written for the rest of us.
>
> By the way, I never mastered Perl 5's regex's.  I used them,
> but could never figure out exactly what I did.  In Perl 6
> I now can throw them together off the top of my head.  It
> is kind of fun.
>
> -T
>
> --
> ~~
> Computers are like air conditioners.
> They malfunction when you open windows
> ~~


Re: .kv ?

2018-09-14 Thread Brad Gilbert
You can read https://en.wikipedia.org/wiki/Option_type for more information

Tell me if you find any of the Perl 6 section confusing.
https://en.wikipedia.org/wiki/Option_type#Perl_6

On Fri, Sep 14, 2018 at 6:21 AM Todd Chester  wrote:
>
> >> On Fri, Sep 14, 2018 at 7:08 AM Todd Chester  >> > wrote:
> >>
> >>
> >>
> >> On 09/14/2018 04:01 AM, Simon Proctor wrote:
> >>  > :D is a type constraint requiring an instantiated (or defined)
> >> object of
> >>  > the given type (or a subtype of it).
> >>  >
> >>  > :U is a type constraint saying you have a container specified for
> >> the
> >>  > given type that hasn't been instantiated.
> >>
> >> Hi Simon,
> >>
> >> Your went over my head.  What the heck is "instantiated"?
> >>
> >> https://www.dictionary.com/browse/instantiate
> >> verb (used with object), in·stan·ti·at·ed, in·stan·ti·at·ing.
> >>
> >>   to provide an instance of or concrete evidence in support
> >>   of (a theory, concept, claim, or the like).
> >>
> >> I am not connecting the dots.
> >>
> >> Is there a list of these guys somewhere, or are these the only two?
> >>
> >> -T
> >>
>
>
>
> On 09/14/2018 04:16 AM, Curt Tilmes wrote:
> > See
> > https://docs.perl6.org/type/Signature#Constraining_defined_and_undefined_values
> >
> > If I say "my Int $x",
> > $x is now an Int, but an undefined Int.
> >
> > If I say "my Int $x = 42",
> > $x is an Int, but set to a defined value, 42.
> >
> > Both are Int:
> >
> > say 42 ~~ Int; # OUTPUT: «True␤»
> > say Int ~~ Int; # OUTPUT: «True␤»
> >
> >
> > There are three type constraint suffixes you can add -- :D (defined), :U
> > (undefined) or :_ (defined or undefined)
> >
> > # Checking a type object
> > say Int ~~ Any:D; # OUTPUT: «False␤»
> > say Int ~~ Any:U; # OUTPUT: «True␤»
> > say Int ~~ Any:_; # OUTPUT: «True␤»
> > # Checking an object instance
> > say 42 ~~ Any:D; # OUTPUT: «True␤»
> > say 42 ~~ Any:U; # OUTPUT: «False␤»
> > say 42 ~~ Any:_; # OUTPUT: «True␤»
> >
> >
> >
>
> Hi Curt,
>
> Beautiful explanation!  I am writing it down tomorrow
> in my keepers file.
>
> Thank you!
>
> -T


Re: .new?

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 6:19 AM Todd Chester  wrote:
>
>
>
> On 09/14/2018 03:34 AM, Simon Proctor wrote:
> > I think the docs of objects (sorry on my phone no link) describe object
> > creation and the default new quite well.
>
> They most probably are and most developers would have no issues
> figuring them out.
>
> If a common user can't make heads or tails out of them, then
> they need some work.  Perl 5's perldocs are wonderfully easy
> to understand.  The developers have their own specifications.
> The Docs need to be understandable by the riff raff.
>
>  > Do a search for objects.
>
> What do you mean?
>
> Can you throw an example at me?

In the Perl 6 docs you often are looking for a subroutine or a method
indiscriminately. So the routine pages pull from both lists dynamically.

That is what happened here.

In the case of `.new()` this is a really bad idea.
That is because every object has a new.

Since the pages for routines pull the method documentation out of its
broader context, it can sometimes be confusing.
The broader context being the pages for the types themselves.

This works decently for things like `.substr()` because there is really
only one type which that works on, and is fairly easy to guess about
the wider context.

In the case of `.new()` there is no way to guess about the wider
context.
It is also one of the methods that most people would just get,
so the documentation for each instance of this method
only describes the differences from the norm.

Basically the documentation for `.new()` needs to be hand-crafted.


Re: need p5/p6 :: help

2018-09-14 Thread Brad Gilbert
lexical means it is only available within that scope,
or in sub-scopes

{
my $a;
{
$a = 42;
}
}
$a  # error

{
sub foo (){}
# my sub foo (){}  # identical
{
foo();
}
}
foo() # error

---

Note that

sub foo (){}

is really short for

my only sub foo (){}

The `only` and the `my` are implied

---

For something to be attached to a namespace
it has to be declared as `our` or `has`.

module Foo {
constant Bar = 42;
# our constant Bar = 42; # identical

our sub foo (){64} # in the namespace
}
say Foo::Bar; # 42
say Baz::foo; # 64

class Baz {
method bar (){42}
# has method bar (){42} # identical

our sub foo (){64}
}
say Baz.bar; # 42
say Baz::foo; # 64
On Fri, Sep 14, 2018 at 6:15 AM Todd Chester  wrote:
>
>  > On 14/09/2018 12:59, Todd Chester wrote:
>  >> Hi All,
>  >>
>  >> I am in the process of converting a YUGE program I wrote in
>  >> Perl 5 to Perl 6.  I used "xx::yy" at lot for readability
>  >> so I could tell where something came from.
>  >>
>  >> I take it "::" means something different is Perl 6 than Perl 5.
>  >>
>  >> $ p6 'use lib "/home/linuxutil"; use PrintColors;
>  >> PrintColors::PrintRed "Hi\n";'
>  >>
>  >> Could not find symbol ''
>  >>in block  at -e line 1
>  >>
>  >> In p5 "PrintColors::PrintRed" means to use the routine called
>  >> "PrintRed" found in a modules called "PrintColors".
>  >>
>  >> Does p6 have an equivalent?
>  >>
>  >> Many thanks,
>  >> -T
>
> On 09/14/2018 04:01 AM, Timo Paulssen wrote:
> > It's important for the PrintRed sub inside PrintColors to be declared
> > "our", otherwise it is "my" scoped, i.e. limited to the lexical extent
> > of the module file.
> >
>
> sub PrintRed   ( $Str ) is export { print color('bold'), color('red'),
> "$Str", color('reset'); }
>
> I have never understood the use of "our" in a module.
> I can't tell the difference.
>
> Also, did you answer my question about "::" and did it
> just go over my head?
>
> The p5 guys use to tell me "its lexiconical", meaning it was figured
> out on the fly.  (Took me forever to catch on.)  Is that any
> relation to your use of the word "lexical"?
>
> https://www.dictionary.com/browse/lexical?s=t
>
> adjective
>
> of or relating to the words or vocabulary of a language,
> especially as distinguished from its grammatical and
> syntactical aspects.
>
> of, relating to, or of the nature of a lexicon.
>
> -T


Re: Multibyte string in Windows command line

2018-09-15 Thread Brad Gilbert
I was just informed by samcv on #perl6-dev that she got the
utf16 stream decoder implemented.
http://colabti.org/irclogger/irclogger_log/perl6-dev?date=2018-09-15#l381

It should be in the next release, so after that there won't be a reason
to do the  dance I described earlier.

The following should just work in the next release.

run $install-file, :out, :enc

On Thu, Sep 13, 2018 at 11:23 PM WFB  wrote:
>
> Never mind. .lines gives back Str and thus .encode is needed...
> Thanks again
>
> On Fri, 14 Sep 2018 at 06:20, WFB  wrote:
>>
>> @Andreas Thanks, I was thinking to do that with regex by myself, but that 
>> would be a ugly workaround and only as a last resort.
>>
>> @Brad: Cool, thanks, I got the errors as well. But did not come up with your 
>> solution. One question, though:
>> >> for $installer.out.lines.map(*.encode('latin1').decode('utf16')) -> $line 
>> >> {
>> Why .encode? I would assume the IO::Handle is allready given back latin-1 
>> because of the :enc<"latin-1"> in the Run command.
>>
>> On Thu, 13 Sep 2018 at 18:20, Brad Gilbert  wrote:
>>>
>>> On Thu, Sep 13, 2018 at 7:22 AM WFB  wrote:
>>> >
>>> > Hi all,
>>> >
>>> > My perl6 runs an executable and prints its output. This output is printed 
>>> > as multibyte string. I assume the executable gives back a multibyte 
>>> > string and perl6 interpret its as one byte string for whatever reasons.
>>> > I tried Run with different encodings like windows-1251, utf16 and so on. 
>>> > No luck.
>>> >
>>> > The string I get looks like that:
>>> > S e t t i n g   u p   f o l d e r   C : \ U s e r s \ w o l f
>>> > Hex:
>>> > 53 00 65 00 74 00 74 00 69 00 6E 00 67 00 20 00 75 00 70 00 20 00 66 00 
>>> > 6F 00 6C 00 64 00 65 00 72 00 20 00 43 00 3A 00 5C 00 55 00 73 00 65 00
>>> >
>>> > Here my program:
>>> >
>>> > my $installer = run $install-file, :out;
>>> > for $installer.out.lines -> $line {
>>> > say $line;
>>> > }
>>> >
>>> > Any idea whats wrong here. A WIndows issue or do I something wrong?
>>> >
>>>
>>> Windows uses UTF16 encoding by default (which you see here), while
>>> Perl 6 uses UTF8 by default.
>>>
>>> You should be able to fix it by setting the encoding
>>> (Note that it should probably be set with :encoding, but that
>>> doesn't work currently)
>>>
>>> run $install-file, :out, :enc
>>>
>>> Though I currently get an error from that.
>>>
>>> Streaming decode NYI for encoding 4
>>>
>>> Also I'm sure I should be able to set it after that line, but it also
>>> produces an error
>>>
>>> > my $installer = run $install-file, :out;
>>> > $installer.out.encoding('utf16');
>>> Cannot assign to an immutable value
>>>
>>> ---
>>>
>>> A work around is to use 'latin1' (almost binary) and use `.encode.decode`
>>>
>>> my $installer = run $install-file, :out, :enc;
>>> for $installer.out.lines.map(*.encode('latin1').decode('utf16')) -> 
>>> $line {
>>> say $line;
>>> }


Re: .kv ?

2018-09-15 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 10:37 PM ToddAndMargo  wrote:
>
> On 09/14/2018 08:09 PM, Brad Gilbert wrote:
> > I think that it is because of how you read.
> >
> > The way your brain figures out what is written, is slow.
>
> That is how the human the human brain works.  It is
> always looking for patterns.  Depth perception for
> instance.  Is that a shadow or an actual hole?
> Sometimes it screws up royally.
>
> "Look See" really did me a disservice.

I'm just saying that brains are wired differently.

Anyway I edited the Option Types post.


Re: need p5/p6 :: help

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 7:10 PM ToddAndMargo  wrote:
>
> On 09/14/2018 04:37 PM, Brandon Allbery wrote:
>
> >  "{$x}::{$y}"
>
> Most of my programming before Perl 5 was bash.  I
> did a lot of "${x}abc" to keep the variables
> from being confused with each other.
>
> I carried the practice over to perl 6 with
> "{$x}abc" but the developers over on the chat
> line told me not to do it.  I don't remember why,
> (I just do everything they tell me.)
>
> Now I just use an escape or a ~

There are some caveats using {} in a string literal

> say "iteration: { ++$ }" xx 5
(iteration: 1 iteration: 1 iteration: 1 iteration: 1 iteration: 1)
> my $a; say "iteration: { ++$a }" xx 5
(iteration: 1 iteration: 2 iteration: 3 iteration: 4 iteration: 5)

That is likely what they were talking about.

Basically these two bits of code are equivelent

"{$x}::{$y}"

"" ~ {$x}() ~ "::" ~ {$y}() ~ ""

So I wouldn't use {} if you can just use the variable itself.


Re: tip: that annoying character at the end

2018-09-14 Thread Brad Gilbert
You can just remove the control characters

   my $x="abc.zip"~chr(7)~chr(138);
   $x .= subst(/<:Cc>+ $/,'');
   say $x;

Note that 13 is carriage return and 10 is newline

If the only ending values are (13,10), 13, or 10
you can use .chomp to remove them

   my $x="abc.zip"~chr(13)~chr(10);
   $x .= chomp;
   say $x;
On Fri, Sep 14, 2018 at 5:22 PM ToddAndMargo  wrote:
>
> Hi All,
>
> A tip to share.
>
> I work a lot with downloaded web pages.  I cut
> out things like revision numbers and download
> locations.
>
> One of the things that use to drive me a bit nuts was that
> web pages can come with all kind of weird line terminators.
> I'd wind up with a link location that bombed because
> there was some weird unprintable character at the end.
>
> Now there are routines to chop off these kind of things,
> but they don't always work, depending on what the weird
> character is.
>
> What I had done in the past as to dump the page to a file
> and use a hex editor to figure out what the weird character
> was.  I have found ascii 0, 7, 10, 12, 13 and some other weird
> ones I can't remember.  They often came is combinations too.
> Then cut the turkey out with a regex.  It was a lot of work.
>
> Now-a-days, it is easy.  I just get "greedy" (chuckle).
> I always know what end of the string should be: .zip,
> .exe, .rpm, etc..  So
>
> $Str ~~ s/ ".zip"  .* /.zip/;
>
> $ p6 'my $x="abc.zip"~chr(7)~chr(138); $x~~s/ ".zip" .* /.zip/; say
> "<$x>";'
> 
>
> Problem solved.  And it doesn't care what the weird character(s)
> at the end is/are.
>
> :-)
>
> Hope this helps someone else.  Thank you for all the
> help you guys have given me!
>
> -T


Re: .kv ?

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 9:42 PM ToddAndMargo  wrote:
>
> On 09/14/2018 07:16 PM, Brad Gilbert wrote:
> > The author greatly appreciates the time spent on writing this critique.
> >
> > (I'm the author)
> >
> > Responses written inline
> >
> > On Fri, Sep 14, 2018 at 4:55 PM ToddAndMargo  wrote:
> >>
> >> On 09/14/2018 09:26 AM, Brad Gilbert wrote:
> >>> You can read https://en.wikipedia.org/wiki/Option_type for more 
> >>> information
> >>>
> >>> Tell me if you find any of the Perl 6 section confusing.
> >>> https://en.wikipedia.org/wiki/Option_type#Perl_6
> >>>
> >>
> >> Hi Brad,
> >>
> >> I had to read to top over very slowly.  Part of the issue was
> >> that I was not taught to read correctly.  (I was taught
> >> "Look See", instead of "Phonics").  I kept seeing other words,
> >> other than "nullable" and "non-nullable".  Eventually, I forced
> >> myself to use phonics and the words made sense.  This is not the
> >> authors problem, but mine alone.
> >
> > Yeah I remember thinking at the time that "non-nullable"
> > might be confusing.
> >
> > When I read, I "hear" the words. (usually in my voice)
> >
> > I will try to take into consideration to not use confusables
> > in the future.
> >
> >>"There are as many null values as there are types, that
> >>is because every type is its own null. So all types are
> >>also their own option type."
> >>
> >> Well stated.  Chuckle, in Modula2 a null is always 0H.
> >
> > If I remember correctly, the only reason I wrote it was
> > so that I could write down those two sentences.
> >
> > I think I even said them out loud to myself.
> >
> >>'To opt into a non-nullable version of a type add the :D
> >>"smiley" to it."
> >>
> >> This is confusing.  And I don't think correct, but I could be wrong.
> >
> > I stayed with the language that is on the rest of the page.
> >
> > It is correct, but it needs some further refinement/clarification.
> >
> > Really I should throw it out, and come up with a new sentence.
> >
> >> Curt stated it a lot better:
> >>
> >> If I say "my Int $x",
> >> $x is now an Int, but an undefined Int.
> >>
> >> If I say "my Int $x = 42",
> >> $x is an Int, but set to a defined value, 42.
> >>
> >> ":D" means that the variable is "defined".  "non-nullable" is
> >> a confusing way to state it.
> >
> > That is not *exactly* what :D means.
> > It means it can only ever be a defined value of that type or subtype.
> >
> > Curt was talking about something slightly different than what that
> > sentence talks about.
> >
> > Perhaps I could have written:
> >
> >  “To exclude null values, a :D "smiley" can be added.”
> >
> > I will think about this further when I am less tired.
> >
> >> It is also possible to opt into a type that is only
> >> ever a nullable using the :U "smiley".
> >>
> >> Curt's description is explains this perfectly. "is only
> >> ever a nullable" is confusing.  ":U" means that the
> >> variable has not got anything assigned to it yet.
> >
> > No, :U means it can **never** have anything other than a null assigned to 
> > it.
> >
> > Your statement was incorrect the moment you added "yet" instead of "ever".
> >
> > This is part of the reason I asked for your input.
> > I wanted to know exactly where your thoughts diverged, and
> > where I was less than clear.
> >
> > Now that I know both, I can hopefully make it so that people
> > who think and read like you do can understand it better.
> >
> >> To me ":D" means that the variable has something assigned to
> >> and ":U" means that the variable has yet to have anything
> >> assigned to it.
> >
> >  my Any:U $t;
> >  $t = Int;
> >  $t = Str;
> >  $t = 42;  # error
> >
> > Again "yet" is the wrong word.
> >
> >> If I were to rewrite this, I'd reverse D and U as that
> >> is the way they evolve.  All variables start out as :U.
> >>
> 

Re: .kv ?

2018-09-14 Thread Brad Gilbert
The author greatly appreciates the time spent on writing this critique.

(I'm the author)

Responses written inline

On Fri, Sep 14, 2018 at 4:55 PM ToddAndMargo  wrote:
>
> On 09/14/2018 09:26 AM, Brad Gilbert wrote:
> > You can read https://en.wikipedia.org/wiki/Option_type for more information
> >
> > Tell me if you find any of the Perl 6 section confusing.
> > https://en.wikipedia.org/wiki/Option_type#Perl_6
> >
>
> Hi Brad,
>
> I had to read to top over very slowly.  Part of the issue was
> that I was not taught to read correctly.  (I was taught
> "Look See", instead of "Phonics").  I kept seeing other words,
> other than "nullable" and "non-nullable".  Eventually, I forced
> myself to use phonics and the words made sense.  This is not the
> authors problem, but mine alone.

Yeah I remember thinking at the time that "non-nullable"
might be confusing.

When I read, I "hear" the words. (usually in my voice)

I will try to take into consideration to not use confusables
in the future.

>   "There are as many null values as there are types, that
>   is because every type is its own null. So all types are
>   also their own option type."
>
> Well stated.  Chuckle, in Modula2 a null is always 0H.

If I remember correctly, the only reason I wrote it was
so that I could write down those two sentences.

I think I even said them out loud to myself.

>   'To opt into a non-nullable version of a type add the :D
>   "smiley" to it."
>
> This is confusing.  And I don't think correct, but I could be wrong.

I stayed with the language that is on the rest of the page.

It is correct, but it needs some further refinement/clarification.

Really I should throw it out, and come up with a new sentence.

> Curt stated it a lot better:
>
>If I say "my Int $x",
>$x is now an Int, but an undefined Int.
>
>If I say "my Int $x = 42",
>$x is an Int, but set to a defined value, 42.
>
> ":D" means that the variable is "defined".  "non-nullable" is
> a confusing way to state it.

That is not *exactly* what :D means.
It means it can only ever be a defined value of that type or subtype.

Curt was talking about something slightly different than what that
sentence talks about.

Perhaps I could have written:

“To exclude null values, a :D "smiley" can be added.”

I will think about this further when I am less tired.

>It is also possible to opt into a type that is only
>ever a nullable using the :U "smiley".
>
> Curt's description is explains this perfectly. "is only
> ever a nullable" is confusing.  ":U" means that the
> variable has not got anything assigned to it yet.

No, :U means it can **never** have anything other than a null assigned to it.

Your statement was incorrect the moment you added "yet" instead of "ever".

This is part of the reason I asked for your input.
I wanted to know exactly where your thoughts diverged, and
where I was less than clear.

Now that I know both, I can hopefully make it so that people
who think and read like you do can understand it better.

> To me ":D" means that the variable has something assigned to
> and ":U" means that the variable has yet to have anything
> assigned to it.

my Any:U $t;
$t = Int;
$t = Str;
$t = 42;  # error

Again "yet" is the wrong word.

> If I were to rewrite this, I'd reverse D and U as that
> is the way they evolve.  All variables start out as :U.
>
>   To designate a variable that does not have a value assigned
>   to it yet and is still in the null state, use the :U designation.
>
>   To designate a variable that must have a value assigned
>   to it (not be in the null state), use the :D designation

I described :D first as that is more useful than :U

It is easier to describe.
It is also the default for the rest of the languages on the page.

After describing :D, it then becomes easier to describe :U
as it is exactly opposite

I may use your description of :D, at least as inspiration.

I will look into this further when I am less tired.

>
> The examples are excellent.
>

Thank you.

I remember worrying that it was so much longer than the rest of the
languages. (It's at least twice as long as the rest).

> Coming from Modula2 and Pasca, one of the issues I had to content
> with when I picked started coding in Perl 5 was that in Modula2
> a variable is just a spot in memory with a designated length.
> A new variable contains whatever junk was in that memory location
> when you started your program.  You very quickly learn to pre-salt
> all your v

Re: Can methods have multiple inputs?

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 6:03 PM ToddAndMargo  wrote:
>
> >> On Fri, Sep 14, 2018 at 6:47 PM ToddAndMargo  >> > wrote:
> >>
> >> Hi All,
> >>
> >> Can a method be given multiple inputs?
> >>
> >>   ( $a, $b ).foo
> >>
> >> and how would the docs write it?
> >>
> >>   method foo(Any:D Any:D:  -->Bool)
> >>
> >> Is there a comma or a space between the two "any"'s?
> >>
> >> Many thanks,
> >> -T
> >>
>
>
>
> On 09/14/2018 03:52 PM, Brandon Allbery wrote:
> > In that case, you're not giving it two items; you are giving it a single
> > List that happens to have two items within it. A method has one
> > invocant. If you are invoking method foo on that, its invocant is a List.
> >
> >  > my $a; my $b; say ($a, $b).^name
> > List
>
> Makes sense.  () turns it into a "List" so it
> can be passed as one.
>
> Thank you!

No () doesn't turn it into a list.

The comma turns it into a list

The () just act as a way to textually encapsulate the list

(42).^name;  # Int
(42, ).^name; # List

This is a very important distinction.

[[[42]]].perl(); # [42]
[[[42],],].perl(); # [[[42],],]

(((42))).perl(); # 42
(((42,),),).perl(); # (((42,),),)


Re: tip: that annoying character at the end

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 7:49 PM ToddAndMargo  wrote:
>
> > On Fri, Sep 14, 2018 at 5:22 PM ToddAndMargo  wrote:
> >>
> >> Hi All,
> >>
> >> A tip to share.
> >>
> >> I work a lot with downloaded web pages.  I cut
> >> out things like revision numbers and download
> >> locations.
> >>
> >> One of the things that use to drive me a bit nuts was that
> >> web pages can come with all kind of weird line terminators.
> >> I'd wind up with a link location that bombed because
> >> there was some weird unprintable character at the end.
> >>
> >> Now there are routines to chop off these kind of things,
> >> but they don't always work, depending on what the weird
> >> character is.
> >>
> >> What I had done in the past as to dump the page to a file
> >> and use a hex editor to figure out what the weird character
> >> was.  I have found ascii 0, 7, 10, 12, 13 and some other weird
> >> ones I can't remember.  They often came is combinations too.
> >> Then cut the turkey out with a regex.  It was a lot of work.
> >>
> >> Now-a-days, it is easy.  I just get "greedy" (chuckle).
> >> I always know what end of the string should be: .zip,
> >> .exe, .rpm, etc..  So
> >>
> >>  $Str ~~ s/ ".zip"  .* /.zip/;
> >>
> >>  $ p6 'my $x="abc.zip"~chr(7)~chr(138); $x~~s/ ".zip" .* /.zip/; say
> >> "<$x>";'
> >>  
> >>
> >> Problem solved.  And it doesn't care what the weird character(s)
> >> at the end is/are.
> >>
> >> :-)
> >>
> >> Hope this helps someone else.  Thank you for all the
> >> help you guys have given me!
> >>
> >> -T
>
>
> On 09/14/2018 05:43 PM, Brad Gilbert wrote:
>  > You can just remove the control characters
>  >
>  > my $x="abc.zip"~chr(7)~chr(138);
>  > $x .= subst(/<:Cc>+ $/,'');
>  > say $x;
>  >
>  > Note that 13 is carriage return and 10 is newline
>  >
>  > If the only ending values are (13,10), 13, or 10
>  > you can use .chomp to remove them
>  >
>  > my $x="abc.zip"~chr(13)~chr(10);
>  > $x .= chomp;
>  > say $x;
>
> Thank you!
>
> "chomp" was on of those routines I could only get
> to work "sometimes".  It depended on what weird character(s)
> I was dealing with.

`chomp` removes a trailing newline.

>
> Would you explain what you are doing with
> $x .= subst(/<:Cc>+ $/,'');

Cc is the Unicode general category for control characters

> say 7.uniprop;
Cc

> say 7.uniprop('General_Category')
Cc

You can match things by category

Like numbers
/ <:N> /
decimal numbers
/ <:Nd> /
letter numbers
/ <:Nl> /
other numbers
/ <:No> /

letters
/ <:L> /
lowercase letters
/ <:Ll> /
uppercase letters
/ <:Lu> /
titlecase letters
/ <:Lt> /

It is exactly the same as

   $x ~~ s/ <:Cc>+ $ //;

Originally I was just going to return the result of .subst()
rather than mutating $x.


Re: tip: that annoying character at the end

2018-09-14 Thread Brad Gilbert
On Fri, Sep 14, 2018 at 10:11 PM ToddAndMargo  wrote:
>
> On 09/14/2018 07:34 PM, Brad Gilbert wrote:
> > $x ~~ s/ <:Cc>+ $ //;
>
> What exactly is <:Cc> again?

< and >  inside of a regular expression is for advanced features

If the first character is   :   then it knows to look for Unicode properties

One of those properties is GeneralCategory.

The General Category for the weird characters is Cc

( I think it is Control, common )

So this works

/ <:GeneralCategory> /

As a shortcut, you can leave off the "GeneralCategory" portion

/ <:Cc> /


Re: how do I do this index in p6?

2018-09-13 Thread Brad Gilbert
On Thu, Sep 13, 2018 at 11:52 PM Todd Chester  wrote:
>
> >> Le jeu. 13 sept. 2018 à 23:12, ToddAndMargo  >> > a écrit :
> >>
> >
> >> $ p6 'constant c=299792458; say c ~" metres per second";'
> >> 299792458 metres per second
> >>
> >> Hm. Now I am wondering how to format the
> >> commas into the say.
> >>
>
>
>
> On 09/13/2018 02:43 PM, Laurent Rosenfeld wrote:
> > Not very pretty, but this works:
> >
> > constant c = 299792458;
> > say c.flip.subst(/(\d**3)/, {"$0,"}, :g).flip.subst(/^\,/, "");
> >
>
> Oh Dude!

It's simpler to use comb and join

constant c = 299792458;
say c.flip.comb(3).join(',').flip;


Re: Please explain this to me

2018-09-16 Thread Brad Gilbert
I think I have an idea of where your thinking is going wrong.
The trouble is going to be to describe it so that you can understand.

First, I think you may be misunderstanding what we mean by defined and
undefined.



So I will use "instance" and "class"

---

class Foo {};

say Foo;  # <- "class" value
say Foo.new(); # <- "instance" value

my $bar = Foo;   # <- "class" value
my $baz = Foo.new(); # <- "instance" value

Foo.defined.say;  # False  # <- "class" value
Foo.new().defined.say; # True  # <- "instance" value

---

In Perl 6 types are both types, and values:

You can store it as a value.

my $a = Int;

I am going to call that a "class" value.

In this example the value is of type "Int".

The "Int" ("class") value is also of type "Int".

You can even pass around "class" values with the type "smiley".

my $a = Int:D;

This is useful in the compiler.

---

If you use it as a type:

my Int $b;

You are saying that it must be an "instance" or a "class" value of that type.

The default value is the same as the type.

So that last example is the same as:

my Int $b = Int;

You can bring it back to the default by assigning a "class" value.

$b = 42;
$b = Int;

If you use a type "smiley" in the type, you constrain it further.

my Int:D $c;  # error

In this case you are saying only "instance" values are allowed.

In that last case the default value is "Int:D", which is a "class"
value, but only "instance" values are allowed by the type.

Note that again the default value is the same as the type, so it
produces an error.

---

The type/value "Nil" is special, as it changes the variable to it's default.

my Int $d is default(42);   # 42
$d = 10;# 10
$d = Nil;   # 42

In this example for it to hold a "class" value, you have to do so explicitly.

   $d = Int;   # Int

---

my Int:U $u;

The "class" values that can be stored in this variable are below

Int
Int:_ # same as previous
Int:U
Int:D

class Other-Int is Int {…}
Other-Int
Other-Int:_ # same as previous
Other-Int:U
Other-Int:D

my \foo = Int but 'Foo'
foo
foo:_ # same as previous
foo:U
foo:D

Note again that I am talking about them as values.

---

When you use a type in a declaration:

my Int $f;

You can think about it as a macro named "my" which takes two arguments.
The first one is a "class" value, and the second one is the name of
the variable.

This makes it so that you can have aliases.

constant Name = Str:D;

my Name $first-name = "Brad";

---

I think where you are going wrong is that other languages also use the
words "defined" and "undefined".

When we use them in Perl 6, we mean something slightly different.

===

You just added a question about :=

:= is the binding operator.

Normally scalar variables store a Scalar that you assign into.

Just think about this:

my $a = 0;

As being short for something like the following fake code:

(my $a := Scalar.new) = 0;

When you use :=, you are basically creating an alias:

my $b;
my $c := $b;

$c = 42;
say $b;  # 42

This also means that if you alias a value, the variable becomes readonly

my $d := 0;
$d = 0;  # error Cannot assign to an immutable value
On Sun, Sep 16, 2018 at 7:49 PM ToddAndMargo  wrote:
>
> On 09/14/2018 08:07 PM, ToddAndMargo wrote:
> > ":D"
> >  means it wants actual data in the string and not a Nil.
> >  The jargon for this requirement is that is is constrained
> >  to an actual value
> >
> >  If it wanted a Nil, it would say ":U" or constrained to
> >  a Nil
>
> Iteration 3:
>
>
> ":D"
>  means it wants the variable "Defined" (Constrained).
>  For example:
>my Str $x;
>my Int $i;
>
>  The value of the variable may be empty but the variable
>  does not become "defined" until a value is places in it.
>  ("Nil" is seen as "Undefined")
>
> ":U"
>  means the variable is "Undefined" (defaults to type "Any")
>
>  For example:
>my $x;
>my $i;
>
>
>
> $ p6 'my $x; if $x.defined {say "Defined"}else{say "Undefined"};'
> Undefined
>
> $ p6 'my Real $x; if $x.defined {say "Defined"}else{say "Undefined"};'
> Undefined
>
> $ p6 'my Real $x=3; if $x.defined {say "Defined"}else{say "Undefined"};'
> Defined
>
> $ p6 'my $x=3; if $x.defined {say "Defined"}else{say "Undefined"};'
> Defined
>
>
> $ p6 'my $x=3; dd $x'
> Int $x = 3
>
> $ p6 'my $x; dd $x'
> Any $x = Any
>
> $ p6 'my Real $x; dd $x'
> Real $x = Real
>
> $ p6 'my Real $x = 3; dd $x'
> Int $x = 3
>
> Huh ??


Re: Multibyte string in Windows command line

2018-09-13 Thread Brad Gilbert
On Thu, Sep 13, 2018 at 7:22 AM WFB  wrote:
>
> Hi all,
>
> My perl6 runs an executable and prints its output. This output is printed as 
> multibyte string. I assume the executable gives back a multibyte string and 
> perl6 interpret its as one byte string for whatever reasons.
> I tried Run with different encodings like windows-1251, utf16 and so on. No 
> luck.
>
> The string I get looks like that:
> S e t t i n g   u p   f o l d e r   C : \ U s e r s \ w o l f
> Hex:
> 53 00 65 00 74 00 74 00 69 00 6E 00 67 00 20 00 75 00 70 00 20 00 66 00 6F 00 
> 6C 00 64 00 65 00 72 00 20 00 43 00 3A 00 5C 00 55 00 73 00 65 00
>
> Here my program:
>
> my $installer = run $install-file, :out;
> for $installer.out.lines -> $line {
> say $line;
> }
>
> Any idea whats wrong here. A WIndows issue or do I something wrong?
>

Windows uses UTF16 encoding by default (which you see here), while
Perl 6 uses UTF8 by default.

You should be able to fix it by setting the encoding
(Note that it should probably be set with :encoding, but that
doesn't work currently)

run $install-file, :out, :enc

Though I currently get an error from that.

Streaming decode NYI for encoding 4

Also I'm sure I should be able to set it after that line, but it also
produces an error

> my $installer = run $install-file, :out;
> $installer.out.encoding('utf16');
Cannot assign to an immutable value

---

A work around is to use 'latin1' (almost binary) and use `.encode.decode`

my $installer = run $install-file, :out, :enc;
for $installer.out.lines.map(*.encode('latin1').decode('utf16')) -> $line {
say $line;
}


Re: binary test and position?

2019-02-01 Thread Brad Gilbert
This would work:

my $b = Buf.new( 0,0,0, 1, 2, 0 );
my $match = Buf.new( 1, 2 );

$b.rotor( $match.elems => 1 - $match.elems ).grep(* eqv $match.List, :k)

If you only need the first one, swap out `grep` for `first`

Another iffy option is to decode it as latin1

$b.decode('latin1').index($match.decode('latin1'))

On Fri, Feb 1, 2019 at 9:22 PM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> On a type Buf, what do I use to check for the
> position of a byte pattern?
>
>
> Many thanks,
> -T


Re: binary test and position?

2019-02-01 Thread Brad Gilbert
`eq` is string equality
`==` is numeric equality

a Buf is neither.

You want `eqv` (equivalent)

$b[2..4] eqv (0x90,0x00,0x04)

On Fri, Feb 1, 2019 at 9:37 PM ToddAndMargo via perl6-users
 wrote:
>
> On 2/1/19 7:22 PM, ToddAndMargo via perl6-users wrote:
> > Hi All,
> >
> > On a type Buf, what do I use to check for the
> > position of a byte pattern?
> >
> >
> > Many thanks,
> > -T
>
>
> Basically, what am I doing wrong here?
>
> $ p6 'my $handle=open("filever.exe", :bin, :ro); my Buf $b; $b=
> $handle.read(5); say $b; say $b[2..4];; if ( $b[2..4] eq 0x90,0x00,0x04
> ) {say "y";} else {say "n"}; $handle.close;'
> Buf[uint8]:0x<4D 5A 90 00 03>
> (144 0 3)
> y
>
>
> I am testing to see if the pattern 0x90 0x00 0x04 exists,
> which is does not.


Re: faster than index?

2019-02-02 Thread Brad Gilbert
`.index` is going to be the fastest because it is directly using NQP
ops which are built into the VM.

'abcdefg'.index('de'); # 3

If you want all of the indexes, use `.indices`

'abcdefabc'.indices('abc'); # 0, 6

`.index` will return `Nil` if it doesn't find anything, and `.indices`
will return an empty list.

'abc'.index('ZZ'); # Nil
'abc'.indices('ZZ'); # ()

To see the actual code implementing these (and other similar methods):

- .index: 
https://github.com/rakudo/rakudo/blob/master/src/core/Str.pm6#L255-L284
- .indices: 
https://github.com/rakudo/rakudo/blob/master/src/core/Str.pm6#L206-L252
- .contains: 
https://github.com/rakudo/rakudo/blob/master/src/core/Str.pm6#L183-L203
- .rindex: 
https://github.com/rakudo/rakudo/blob/master/src/core/Str.pm6#L294-L323

On Sat, Feb 2, 2019 at 5:13 AM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> What is the fastest way to find the index of
> a sub string in a string?
>
> -T


Re: Start reading at a specific index?

2019-02-02 Thread Brad Gilbert
`$whence` means “whence”
adverb
   1.
from what place or source.

So it should be one of the values of the `SeekType` enum

say SeekType.enums.keys
# (SeekFromCurrent SeekFromBeginning SeekFromEnd)

- `SeekFromCurrent` means it is relative to where it is currently (go
forward/backward)

$fh.read(1);
$fh.seek( -1, SeekFromCurrent);
$fh.read(1); # same as previous `.read`

# pretend to have read 5 bytes
$fh.seek( 5, SeekFromCurrent );

- `SeekFromBeginning` means absolute position.

# restart at beginning, and then skip forward 5 bytes
$fh.seek( 5, SeekFromBeginning );

- `SeekFromEnd` means absolute position, except starting at the end of the file

$fh.seek( -1, SeekFromEnd );
$fh.read(1); # read last byte

On Sat, Feb 2, 2019 at 9:02 PM ToddAndMargo via perl6-users
 wrote:
>
> On 2/2/19 3:16 AM, Shlomi Fish wrote:
> > On Sat, 2 Feb 2019 01:08:39 -0800
> > ToddAndMargo via perl6-users  wrote:
> >
> >> Hi All,
> >>
> >> Is there a way to modify this to start reading at
> >> a specific index?  And include how many bytes (300)
> >> to read as well?
> >>
> >>my $FileHandle = open( $FileName, :bin, :ro );
> >>my Buf $BinaryFile = $FileHandle.read( 300 );
> >>
> >> Many thanks,
> >> -T
> >
> > See https://docs.perl6.org/routine/seek .
> >
> >
>
>
> Thank you!
>
>
> I am not sure exactly what they mean by "$whence".
>
> method seek(IO::Handle:D: Int:D $offset, SeekType:D $whence --> True)
>
>  SeekFromBeginning: The beginning of the file.
>
> my Bool $GoodRead = seek($FileHandle, $offset, SeekFromBeginning );
> my Bool $GoodRead = seek.$FileHandle( $offset, SeekFromBeginning );
>
> Or do I need to assign something to a variable called "$whence"?
>
> Many thanks,
> -T
>
>
>
> --
> ~~
> Computers are like air conditioners.
> They malfunction when you open windows
> ~~


Re: binary test and position?

2019-02-02 Thread Brad Gilbert
Subs do not need to have a `return` statement if it is returning the last value.

You also broke the return value of the subroutine that I wrote by
assigning it to a variable.

What I wrote would return `Nil` if it failed to find a match, yours
will return an undefined `Int`.
It should return `Nil` because that is what `index` would return.

Doing bytewise conversion from Buf to Str is pointless. It will break
on Unicode data.
It would also be exactly the same as converting ASCII if it worked.
(It won't work on binary data)

If you are dealing with something that is mostly Unicode but also has
binary data
decode using 'utf8-c8'.

If you are dealing with something that is mostly binary, decode using 'latin1',
or just use raw bytes in a buffer.

my Buf $buffer = $fh.read(10);
my Str $string = $buffer.decode('latin1');

# the first three bytes were really a Utf8 encoded character
my Str $char = $string.substr(0,3).encode('latin1').decode('utf8');
# or
my Str $char = $buffer.subbuf(0,3).decode('utf8');

Also note that `encode` doesn't always return a Buf.

my Buf $buf = Buf.new( 'hello'.encode('utf8') );

---

The subroutine I wrote was simplified to work for an Array or List, not a Buf.

It is also weird that you are using CamelCase for variables,
and a mixture of CamelCase and snake-case for the subroutine name.


Improving your variant, and changing it so the second parameter is a Buf.

sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
my List $Matcher = $SubBuf.List; # only call .List once
my Any $Position is default(Nil) = Nil;
my Int $Elems = $Matcher.elems;

$Position = $Buffer.rotor($Elems => 1- $Elems).first(* eqv
$Matcher, :k);
return $Position;
}

`$Position` has to be `Any` (or `Mu`) so that it can store the value `Nil`.
`Nil` sets a variable to its default, so we have to change the default
with `is default(Nil)`.
(The normal default is the same as the container type)
(The `= Nil;` is always pointless in the declaration of a `$scalar` variable.)

One simplification is to just have the return value as the last thing
in the subroutine without a `return`.
(It may also be slightly faster, but not by much.)

sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
my List $Matcher = $SubBuf.List;
my Any $Position is default(Nil) = Nil;
my Int $Elems = $Matcher.elems;

$Position = $Buffer.rotor($Elems => 1- $Elems).first(* eqv
$Matcher, :k);
$Position; # <
}

Assignment is a rvalue, so we can remove that last line

sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
my List $Matcher = $SubBuf.List;
my Any $Position is default(Nil) = Nil;
my Int $Elems = $Matcher.elems;

$Position = $Buffer.rotor($Elems => 1- $Elems).first(* eqv
$Matcher, :k);
# <---
}

`$Position` is now completely pointless.

sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
my List $Matcher = $SubBuf.List;
my Int $Elems = $Matcher.elems;

$Buffer.rotor($Elems => 1- $Elems).first(* eqv $Matcher, :k);
# ^
}

If you want `return` (even though it isn't doing anything)

sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
my List $Matcher = $SubBuf.List;
my Int $Elems = $Matcher.elems;

return $Buffer.rotor($Elems => 1- $Elems).first(* eqv $Matcher, :k);
# ^
}

You could also declare the type of the return value

sub Buf-Index ( Buf $Buffer, Buf $SubBuf --> Int ) { # <
my List $Matcher = $SubBuf.List;
my Int $Elems = $Matcher.elems;

return $Buffer.rotor($Elems => 1- $Elems).first(* eqv $Matcher, :k);
}

Note that `Nil` can sneak around the return value type check.

---

As an added bonus, here is a subroutine that returns all of the indices.
(Note that the only differences are `grep` rather than `first`, and
the return type)

sub Buf-Indices ( Buf $Buffer, Buf $SubBuf --> Seq ) {
my List $Matcher = $SubBuf.List;
my Int $Elems = $Matcher.elems;

return $Buffer.rotor($Elems => 1- $Elems).grep(* eqv $Matcher, :k);
}

}

On Sat, Feb 2, 2019 at 10:05 PM ToddAndMargo via perl6-users
 wrote:
>
> On 2/2/19 6:09 AM, Brad Gilbert wrote:
> >  sub buf-index ( Buf $buf, +@match ) {
> >  my $elems = @match.elems;
> >  $buf.rotor( $elems => 1 - $elems ).first(* eqv @match.List, :k)
> >  }
> >
> >  my $buf = Buf[uint8].new(0x4D, 0x5A, 0x90, 0x00, 0x03);
> >
> >  say buf-index( $buf, (0x90, 0x00, 0x03)); # 2
>
> What did I do wrong?
>
> First I did a byte wise conversion of
>
> Buf $BinaryFile   to   Str $StrFile
>
> and
>
> Buf $VersionInfoBuf  to  Str $VersionInfoStr
>
>
>
> sub Buf-Index ( Buf $Buffer, +@SubBuf ) {
> # `index` for buffers
> # $Buffer is the buff

Re: Fastest way to convert from a Buf to a Str?

2019-02-02 Thread Brad Gilbert
This:

for ( @$BinaryFile ) -> $Char { $StrFile ~= chr($Char); }

is better written as

my $StrFile = $BinaryFile.map(*.chr).reduce(* ~ *);

It is also exactly equivalent to just e

# if $BinaryFile is a Buf
my $StrFile = $BinaryFile.decode('latin1');

# if it isn't
my $StrFile = Buf.new($BinaryFile).decode('latin1');

If you don't otherwise need $BinaryFile

my $fh = open 'test', :enc('latin1');
my $StrFile = $fh.slurp;

or

my $StrFile = 'test'.IO.slurp(:enc('latin1'));

---

Buf and Str used to be treated more alike, and it was very confusing.

There should be more methods on Buf that work like the methods on Str,
but that is about it.

Having a string act like a buffer in Modula 2 probably works fine
because it barely supports Unicode at all.

Here is an example of why it can't work like that in Perl6:

my $a = 'a';
my $b = "\c[COMBINING ACUTE ACCENT]";

my $c = $a ~ $b;
my $d = $a.encode ~ $b.encode;
my $e = Buf.new($a.encode) ~ Buf.new($b.encode);

say $a.encode; # utf8:0x<61>
say $b.encode; # utf8:0x

say $c.encode; # utf8:0x

say $d; # utf8:0x<61 CC 81>
say $e; # Buf:0x<61 CC 81>

Notice that `$c.encode` and `$d` are different even though they are
made from the same parts.
`$d` and `$e` are similar because they are dealing with lists of
numbers not strings.

On Sat, Feb 2, 2019 at 9:23 PM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> I need to read a file into a buffer (NO CONVERSIONS!)
> and then convert it to a string (again with no
> conversions).
>
> I have been doing this:
>
> for ( @$BinaryFile ) -> $Char { $StrFile ~= chr($Char); }
>
> But it takes a bit of time.  What is the fastest way to do this?
>
> I guess there is not a way to create/declare a variable that is
> both Buf and Str at the same time?  That would mean I did not
> have to convert anything.  I use to get away with this under
> Module 2 all the time.
>
> $ p6 'my $B = Buf.new(0x66, 0x66, 0x77); $B.Str ~= "z";'
> Cannot use a Buf as a string, but you called the Str method on it
>in block  at -e line 1
>
> $ p6 'my $B = Buf.new(0x66, 0x66, 0x77); Str($B) ~= "z";'
> Cannot use a Buf as a string, but you called the Str method on it
>in block  at -e line 1
>
>
> Many thanks,
> -T
>
> --
> 
> A computer without Microsoft is like
> a chocolate cake without the mustard
> 


Re: binary test and position?

2019-02-02 Thread Brad Gilbert
sub buf-index ( Buf $buf, +@match ) {
my $elems = @match.elems;
$buf.rotor( $elems => 1 - $elems ).first(* eqv @match.List, :k)
}

my $buf = Buf[uint8].new(0x4D, 0x5A, 0x90, 0x00, 0x03);

say buf-index( $buf, (0x90, 0x00, 0x03)); # 2

On Fri, Feb 1, 2019 at 11:02 PM ToddAndMargo via perl6-users
 wrote:
>
> On 2/1/19 8:26 PM, ToddAndMargo via perl6-users wrote:
> > On 2/1/19 8:07 PM, ToddAndMargo via perl6-users wrote:
> >> On 2/1/19 8:03 PM, ToddAndMargo via perl6-users wrote:
> >>>  > On Fri, Feb 1, 2019 at 9:37 PM ToddAndMargo via perl6-users
> >>>  >  wrote:
> >>>  >>
> >>>  >> On 2/1/19 7:22 PM, ToddAndMargo via perl6-users wrote:
> >>>  >>> Hi All,
> >>>  >>>
> >>>  >>> On a type Buf, what do I use to check for the
> >>>  >>> position of a byte pattern?
> >>>  >>>
> >>>  >>>
> >>>  >>> Many thanks,
> >>>  >>> -T
> >>>  >>
> >>>  >>
> >>>  >> Basically, what am I doing wrong here?
> >>>  >>
> >>>  >> $ p6 'my $handle=open("filever.exe", :bin, :ro); my Buf $b; $b=
> >>>  >> $handle.read(5); say $b; say $b[2..4];; if ( $b[2..4] eq
> >>> 0x90,0x00,0x04
> >>>  >> ) {say "y";} else {say "n"}; $handle.close;'
> >>>  >> Buf[uint8]:0x<4D 5A 90 00 03>
> >>>  >> (144 0 3)
> >>>  >> y
> >>>  >>
> >>>  >>
> >>>  >> I am testing to see if the pattern 0x90 0x00 0x04 exists,
> >>>  >> which is does not.
> >>>
> >>>
> >>> On 2/1/19 7:57 PM, Brad Gilbert wrote:
> >>>> `eq` is string equality
> >>>> `==` is numeric equality
> >>>>
> >>>> a Buf is neither.
> >>>>
> >>>> You want `eqv` (equivalent)
> >>>>
> >>>>  $b[2..4] eqv (0x90,0x00,0x04)
> >>>>
> >>>
> >>> That was it.  Thank you!
> >>>
> >>> $ p6 'my $handle=open("filever.exe", :bin, :ro); my Buf $b; $b=
> >>> $handle.read(5); say $b; if ( $b[2..4] eqv (0x90,0x00,0x03) ) {say
> >>> "y";} else {say "n"}; $handle.close;'
> >>> Buf[uint8]:0x<4D 5A 90 00 03>
> >>> y
> >>>
> >>> $ p6 'my $handle=open("filever.exe", :bin, :ro); my Buf $b; $b=
> >>> $handle.read(5); say $b; if ( $b[2..4] eqv (0x90,0x00,0x04) ) {say
> >>> "y";} else {say "n"}; $handle.close;'
> >>> Buf[uint8]:0x<4D 5A 90 00 03>
> >>> n
> >>
> >>
> >> How do I find the position of a pattern in a Buf?
> >
> > Need `pos` for Buf
>
> Actually I do believe it is the binary equivalent of `index` I
> am looking for
>
> --
> ~~
> Computers are like air conditioners.
> They malfunction when you open windows
> ~~


Re: "index" source code?

2019-02-03 Thread Brad Gilbert
The Rakudo Perl6 compilier is written in Perl6 (and a subset of Perl6 named NQP)

The `index` subroutines are at
https://github.com/rakudo/rakudo/blob/64c88f919841c58f5a6dffd3581770e06a8fd6a5/src/core/Cool.pm6#L276-L282

proto sub index($, $, $?, *%) {*}
multi sub index(Cool $s, Cool $needle --> Int:D) {
$s.index($needle)
}
multi sub index(Cool $s, Cool $needle, Cool $pos --> Int:D) {
$s.index($needle,$pos)
}

They basically only call the `index` and `rindex` methods

To keep from showing you all of the methods, they all coerce the value
to Str then call `index` on that.

The location of the Str.index methods is
https://github.com/rakudo/rakudo/blob/3d581c8d23e0b47fd09616a1165f84568531a4aa/src/core/Str.pm6#L255-L284

proto method index(|) {*}
multi method index(Str:D: Cool:D $needle --> Int:D) {
self.index: $needle.Str
}
multi method index(Str:D: Str:D $needle --> Int:D) {
nqp::if(
  nqp::islt_i((my int $i =
nqp::index($!value,nqp::getattr($needle,Str,'$!value'))),
0
  ),
  Nil,
  nqp::p6box_i($i)
)
}
multi method index(Str:D: Cool:D $needle, Cool:D $pos --> Int:D) {
self.index: $needle.Str, $pos.Int
}
multi method index(Str:D: Str:D $needle, Int:D $pos --> Int:D) {
nqp::if(
  nqp::isbig_I(nqp::decont($pos)) || nqp::islt_i($pos,0),
  self!INDEX-OOR($pos),
  nqp::if(
nqp::islt_i((my int $i = nqp::index(
  $!value,nqp::getattr($needle,Str,'$!value'),$pos
)),0),
Nil,
nqp::p6box_i($i)
  )
)
}

Note that they heavily use NQP opcodes, so you shouldn't try and copy them.

On Sun, Feb 3, 2019 at 12:35 AM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> Was the subroutine "index" written Perl6?  If so,
> where can I view the source code?
>
> Many thanks,
> -T


Re: binary test and position?

2019-02-05 Thread Brad Gilbert
`index` is an NQP op, which means in this case that it is written in C
(assuming you are using MoarVM)

https://github.com/MoarVM/MoarVM/blob/ddde09508310a5f60c63474db8f9682bc922700b/src/strings/ops.c#L557-L656

The code I gave for finding a Buf inside of another one was quickly
made in a way to prevent certain bugs from even being possible.


I rewrote it using knowledge of the internals to be a bit faster:

sub blob-index ( Blob:D $buffer, Blob:D $needle, UInt:D $init = 0
--> Int ) {
use nqp;
my int $needle-width = $needle.elems;
my int $elems = $buffer.elems;

if $elems < $needle-width + $init {
fail 'needle is larger than the buffer'
}

my uint $from = $init;
my uint $to   = $from + $needle-width - 1;

loop ( ; $to < $elems ; ++$from,++$to ) {
return $from if $needle eq nqp::slice($buffer,$from,$to)
# eq is safe since they are two Blobs/Bufs
}
return Nil
}

It's faster mainly because it doesn't use an iterator.

This was quickly written.

Note that Buf is a subtype of Blob, so it will also work if given a Buf.

It could be written to be faster, but it still isn't going to be as
fast as `index`.
For one `index` uses a subroutine named `knuth_morris_pratt_string_index`.

---

Also Unicode strings are not stored flat in MoarVM

'a' x 10

That is stored something like the following internally.

REPEAT( STR('a'), 10 )

What this means is that if you are looking for a 'b' for example, it
could check the first repetition for 'b', and skip the rest of the
REPEAT.
That would save 9 string comparisons in this example.

That is not how Bufs are stored in Perl6 at all.
They are declared with `is repr('VMArray')` which basically means they
are stored as C arrays.

On Tue, Feb 5, 2019 at 1:47 AM ToddAndMargo via perl6-users
 wrote:
>
> On 2/2/19 9:29 PM, Brad Gilbert wrote:
> > Subs do not need to have a `return` statement if it is returning the last 
> > value.
> >
> > You also broke the return value of the subroutine that I wrote by
> > assigning it to a variable.
> >
> > What I wrote would return `Nil` if it failed to find a match, yours
> > will return an undefined `Int`.
> > It should return `Nil` because that is what `index` would return.
> >
> > Doing bytewise conversion from Buf to Str is pointless. It will break
> > on Unicode data.
> > It would also be exactly the same as converting ASCII if it worked.
> > (It won't work on binary data)
> >
> > If you are dealing with something that is mostly Unicode but also has
> > binary data
> > decode using 'utf8-c8'.
> >
> > If you are dealing with something that is mostly binary, decode using 
> > 'latin1',
> > or just use raw bytes in a buffer.
> >
> >  my Buf $buffer = $fh.read(10);
> >  my Str $string = $buffer.decode('latin1');
> >
> >  # the first three bytes were really a Utf8 encoded character
> >  my Str $char = $string.substr(0,3).encode('latin1').decode('utf8');
> >  # or
> >  my Str $char = $buffer.subbuf(0,3).decode('utf8');
> >
> > Also note that `encode` doesn't always return a Buf.
> >
> >  my Buf $buf = Buf.new( 'hello'.encode('utf8') );
> >
> > ---
> >
> > The subroutine I wrote was simplified to work for an Array or List, not a 
> > Buf.
> >
> > It is also weird that you are using CamelCase for variables,
> > and a mixture of CamelCase and snake-case for the subroutine name.
> >
> >
> > Improving your variant, and changing it so the second parameter is a Buf.
> >
> >  sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
> >  my List $Matcher = $SubBuf.List; # only call .List once
> >  my Any $Position is default(Nil) = Nil;
> >  my Int $Elems = $Matcher.elems;
> >
> >  $Position = $Buffer.rotor($Elems => 1- $Elems).first(* eqv
> > $Matcher, :k);
> >  return $Position;
> >  }
> >
> > `$Position` has to be `Any` (or `Mu`) so that it can store the value `Nil`.
> > `Nil` sets a variable to its default, so we have to change the default
> > with `is default(Nil)`.
> > (The normal default is the same as the container type)
> > (The `= Nil;` is always pointless in the declaration of a `$scalar` 
> > variable.)
> >
> > One simplification is to just have the return value as the last thing
> > in the subroutine without a `return`.
> > (It may also be slightly faster, but not by much.)
> >
> >  sub Buf-Index ( Buf $Buffer, Buf $SubBuf ) {
> >  my List $Matcher = $SubBuf.List;
> >  my Any $Position is default(Nil) 

Re: split and nils?

2019-02-07 Thread Brad Gilbert
to real Perl6

use v6;
my Str $e = substr( $c, 0, 1 ) ~ substring( $c, 1, 1 );

So if Perl6 did treat Str as an Array, then it would be slower, and
use more memory.
It also might not be able handle Unicode correctly.

Also my guess is that the majority of string related bugs in other languages are
caused by them treating strings as an array of characters.


On Wed, Feb 6, 2019 at 1:56 PM ToddAndMargo via perl6-users
 wrote:
>
>  > On Tue, Feb 5, 2019 at 11:05 PM ToddAndMargo via perl6-users
>  >  wrote:
>  >>
>  >> Hi All,
>  >>
>  >> What is with the starting ending Nils?  There are only four
>  >> elements, why now six?
>  >>
>  >> And how to I correct this?
>  >>
>  >> $ p6 'my Str $x="abcd";
>  >>for split( "",@$x ).kv -> $i,$j {
>  >>say "Index <$i> = <$j> = ord <" ~ ord($j) ~ ">";}'
>  >>
>  >> Use of Nil in string context
>  >> in block  at -e line 1
>  >> Index <0> = <> = ord <> <- nil ???
>  >> Index <1> =  = ord <97>
>  >> Index <2> =  = ord <98>
>  >> Index <3> =  = ord <99>
>  >> Index <4> =  = ord <100>
>  >> Use of Nil in string context
>  >> in block  at -e line 1
>  >> Index <5> = <> = ord <> <- nil ???
>  >>
>  >>
>  >> Many thanks,
>  >> -T
>
> On 2/6/19 5:19 AM, Brad Gilbert wrote:
> > The reason there is a Nil, is you asked for the ord of an empty string.
> >
> >  "".ord =:= Nil
> >
> > The reason there are two empty strings is you asked for them.
> >
> > When you split with "", it will split on every character boundary,
> > which includes before the first character, and after the last.
> > That's literally what you asked for.
> >
> >  my Str $x = "abcd";
> >  say split( "", $x ).perl;
> >  # ("", "a", "b", "c", "d", "").Seq
> >
> > Perl6 doesn't treat this as a special case like other languages do.
> > You basically asked for this:
> >
> >  say split( /  |  /, $x ).perl;
> >  # ("", "a", "b", "c", "d", "").Seq
> >
> > Perl6 gave you what you asked for.
> >
> > That is actually useful btw:
> >
> >  say split( "", "abcd" ).join("|");
> >  # |a|b|c|d|
> >
> > You should be using `comb` if you want a list of characters not `split`.
> >
> >  # these are all identical
> >  'abcd'.comb.kv
> >  'abcd'.comb(1).kv
> >  comb( 1, 'abcd' ).kv
> >
> > Also why did you add a pointless `@` to `$x` ?
> > (Actually I'm fairly sure I know why.)
> >
>
> Hi Brad,
>
> Thank you!
>
> So it is a "feature" of split.  Split sees the non-existent
> index before the start and the non-existent index after
> the end as something.  Mumble. Mumble.
>
> To answer you question about the stray "@".  I forgot
> to remove it.
>
> But it brings up an inconsistency in Perl 6.
>
> This works and also is the source of the stay "@" I forgot
> to remove from the split example.
>
>
> $ p6 'my Buf $x=Buf.new(0x66,0x61,0x62,0x63); for @$x.kv -> $i, $j {say
> "Index <$i> = <$j> = chr <" ~ chr($j) ~ ">";}'
>
> Index <0> = <102> = chr 
> Index <1> = <97> = chr 
> Index <2> = <98> = chr 
> Index <3> = <99> = chr 
>
>
>
> So, this should also work, but does not:
>
> $ p6 'my Str $x="abcd"; for @$x.kv -> $i, $j {say "Index <$i> = <$j> =
> ord <" ~ ord($j) ~ ">";}'
>
> Index <0> =  = ord <97>
>
>
> Strings only have one index (0) and why we have the substr command.
>
> $ p6 'my Str $x="abcd"; say $x[0];'
> abcd
>
>
> So all the rules for other arrays go out the window for
> a Str.  A string is an array of one cell.  And if I
> truly want an array of characters, I need to use Buf
> and not Str.  Only problem is that Str has all the cool
> tools.
>
> -T


Re: split and nils?

2019-02-06 Thread Brad Gilbert
The reason there is a Nil, is you asked for the ord of an empty string.

"".ord =:= Nil

The reason there are two empty strings is you asked for them.

When you split with "", it will split on every character boundary,
which includes before the first character, and after the last.
That's literally what you asked for.

my Str $x = "abcd";
say split( "", $x ).perl;
# ("", "a", "b", "c", "d", "").Seq

Perl6 doesn't treat this as a special case like other languages do.
You basically asked for this:

say split( /  |  /, $x ).perl;
# ("", "a", "b", "c", "d", "").Seq

Perl6 gave you what you asked for.

That is actually useful btw:

say split( "", "abcd" ).join("|");
# |a|b|c|d|

You should be using `comb` if you want a list of characters not `split`.

# these are all identical
'abcd'.comb.kv
'abcd'.comb(1).kv
comb( 1, 'abcd' ).kv

Also why did you add a pointless `@` to `$x` ?
(Actually I'm fairly sure I know why.)

On Tue, Feb 5, 2019 at 11:05 PM ToddAndMargo via perl6-users
 wrote:
>
> Hi All,
>
> What is with the starting ending Nils?  There are only four
> elements, why now six?
>
> And how to I correct this?
>
> $ p6 'my Str $x="abcd";
>   for split( "",@$x ).kv -> $i,$j {
>   say "Index <$i> = <$j> = ord <" ~ ord($j) ~ ">";}'
>
> Use of Nil in string context
>in block  at -e line 1
> Index <0> = <> = ord <> <- nil ???
> Index <1> =  = ord <97>
> Index <2> =  = ord <98>
> Index <3> =  = ord <99>
> Index <4> =  = ord <100>
> Use of Nil in string context
>in block  at -e line 1
> Index <5> = <> = ord <> <- nil ???
>
>
> Many thanks,
> -T


Re: shift left syntax?

2019-02-08 Thread Brad Gilbert
The `=` infix operator is a meta operator.

That means it takes an infix operator as a sort of "argument".

There is no `+=` operator, it is just the `=` operator combined with
the `+` operator.

$a += 2;
$a [+]= 2; # more explicitly take the + operator as an argument to
the = operator

So if you want to know how to use a similar operator to `+=`, start
with the infix operator you want, and add `=`

$i = $i +< 0x01;

$i [+<]= 0x01;
$i +<= 0x01;

On Fri, Feb 8, 2019 at 12:20 AM Todd Chester via perl6-users
 wrote:
>
> Hi All,
>
> Is this the only way to shift left?
>
>$i = $i +< 0x01
>
> $ p6 'my int32 $i=0x5DAE; say $i.base(0x10); $i = $i +< 0x01; say
> $i.base(0x10);'
>
> 5DAE
> BB5C
>
>
> Does we have any of those fancy += ~= ways of doing it?
>
> Many thanks,
> -T


Re: buf to integer?

2019-02-08 Thread Brad Gilbert
If you have a new enough version of Rakudo:

my Buf $x=Buf.new(0xAE,0x5D,0x5C,0x72);

my int32 $i = $x.read-int32(0,LittleEndian);

say $i.base(16);
# 725C5DAE

On Fri, Feb 8, 2019 at 12:35 AM Todd Chester via perl6-users
 wrote:
>
> Hi All,
>
> I am dealing with a Buf what includes 32 bit integers, but
> they are entered somewhat backwards as view with hexedit:
>
> AE 5D 5C 72 represents the number 725C5DAE
>
> This is what I have come up with to convert this type of
> number in a buffer to and integer
>
> $ p6 'my Buf $x=Buf.new(0xAE,0x5D,0x5C,0x72); my int32 $i=$x[3] +< 0x18
> +  $x[2] +< 0x10  +  $x[1] +< 0x08  +  $x[0];  say $x; say $i.base(0x10);'
>
> Buf:0x
> 725C5DAE
>
>
> Is there a more "elegant" way to do this?
>
> Many thanks,
> -T


Re: Typed Arrays and for-loops

2019-02-13 Thread Brad Gilbert
The problem with `$files` is the `$`

When a `for` loop sees something that is itemized / containerized
(`$`) it treats it as a singular value.

my @a = 1,2,3;
my $a = @a;

for @a { .say }
# 1
# 2
# 3

for $a { .say }
# [1 2 3]

for @a.item { .say }
# [1 2 3]

To get it to not see the `$` you have to do something

for $a.list {…}
for @$a {…}

for $a<> {…} # decontainerize
for $a.sefl {…} # ditto

On Wed, Feb 13, 2019 at 6:30 AM Mikkel  wrote:
>
> Hello. (recurring noob-question here)
>
> I seem always seem to get myself confused with Arrays/Typed Arrays. Can I ask 
> of you to explain why the 'for' loop does not work without .flat? It seems so 
> counter intuitive
>
> > my Array[Str] $files;
> (Array[Str])
>
> > $files.push("Test");
> [Test]
>
> > $files.push("Test 2");
> [Test Test 2]
>
> > for $files -> Str $f {.say}
> Type check failed in binding to parameter '$f'; expected Str but got 
> Array[Str] (Array[Str].new("Test", "Test 2"))
>   in block  at  line 1
>
> Best regards
> Mikkel Birkedam


Re: list comprehension

2019-02-11 Thread Brad Gilbert
Actually I would suggest NOT adding Perl6, because the best way to
create a Set is not to use “list comprehension”, but to just call
`.Set`

That whole page is about Set Builder Notation, but Perl6 doesn't
actually have such a thing.

You create a Set through a method call, or a subroutine call.

That is true even in the translations I did.

The closest one is where I added a circumfix operator.

my sub circumfix:«{ }» ( \L ) { L.Set };

I mean this:

Set.new: gather { for L { take $_ } };

can be simplified to:

Set.new( L );

Or if you're being pedantic:

Set.new( L.Seq );

On Mon, Feb 11, 2019 at 12:51 PM mimosinnet  wrote:
>
> Dear Brad,
>
> Thanks very much for the answer. I have been playing with your examples in the
> code below (and learned a lot!). Based on your insight, I would suggest these
> solutions to be added to the wikipedia:
> https://en.wikipedia.org/wiki/Set-builder_notation#Parallels_in_programming_languages
>
> Example1: Set.new: gather { for L { take $_ } };
> Example2: Set.new: cross( K, X.grep: P(x) );
>
> Cheers!
>
> <--- Working code
> my \L = 1..10; my \K = 1..10; my \X = 5..15;
>
> # Example 1
> my $e1 = Set.new: gather { for L { take $_ } };
>
> # Example 2
> my $s1 = Set.new: gather {
>for K -> \k {
>for X -> \x {
>if x < 8 {
>take (k,x);
>}
>}
>}
> }
> my $s2 = Set.new: (K X[,] X).grep: -> ( \k, \x ) { x < 8 };
> my $s3 = Set.new: ( -> \x { |(-> \k { (k,x) if x < 8 } for K) } for X );
> my $s4 = Set.new: gather { -> \k { -> \x { take (k,x) if x < 8; } for X } for 
> K }
> my $s5 = Set.new: cross( K, X.grep: * < 8 );
>
> say $e1; say $s1; say $s2; say $s3; say $s4; say $s5;
> <---
>
> El Sunday, 10 de February del 2019 a les 12:05, Brad Gilbert va
> escriure:
>
> >In
> >
> > {l for l in L}
> >
> >The reason it is in `{}` is to create a Set from iterating over `L`.
> >
> >> In Python, the set-builder's braces are replaced with square brackets, 
> >> parentheses, or curly braces, giving list, generator, and set objects, 
> >> respectively.
> >
> >So in Python:
> >
> >[ l for l in L ] gives a list
> >( l for l in L ) gives a generator
> >{ l for l in L } gives a set
> >
> >In Perl6 those would most likely be written as:
> >
> >L.List   or   L.Array   or   L.list
> >L.Seq
> >L.Set
> >
> >---
> >
> >The way to do that is
> >
> >my \L = ((1..10) xx 3).flat.pick(*).list;
> >
> >set( L ) # A
> >L.Set # B
> >
> >my %set is SetHash;
> >{ ++%set{$_} for L }  # C
> >
> ># D
> >do {
> ># add the {} syntax to create a Set (lexically)
> >my sub circumfix:«{ }» ( \L ) { L.Set };
> >
> >{ $_ for L } # <--
> >}
> >
> >Something that seems similar to me is `unique`
> >
> >.say for L.unique;
> >
> >By that I mean, some places where you would use a Set, it makes sense
> >to use `.unique` instead
> >
> >---
> >
> >As for `{(k, x) for k in K for x in X if P(x)}`
> >
> >The easiest one to directly translate appears to be the Scala one
> >
> >my \K = 1..10;
> >my \X = 5..15;
> >
> ># for (k <- K; x <- X if P(x)) yield (k,x)
> >Set.new: gather {
> >for K -> \k {
> >for X -> \x {
> >if P(x) {
> >take (k,x);
> >}
> >}
> >}
> >}
> >
> >Other ways:
> >
> >Set.new: (K X[,] X).grep: -> ( \k, \x ) { P(x) }
> >
> >Set.new: K X[,] X.grep: 
> >
> >Set.new: K X[,] X.grep: 
> >
> >Set.new: ( -> ( \k, \x ) { (k,x) if P(x) } for K X[,] X )
> >
> >Set.new: ( -> \x { |(-> \k { (k,x) if P x } for K) } for X)
> >
> >On Sun, Feb 10, 2019 at 10:26 AM mimosinnet  wrote:
> >>
> >> Hi all,
> >>
> >> I wonder what would be the Perl notation for 'set-builders', as exposed
> >> in this wikipedia article:
> >>
> >> https://en.wikipedia.org/wiki/Set-builder_notation#Parallels_in_programming_languages
> >>
> >> This is the Python notation:
> >>
> >> Example 1: {l for l in L}
> >> Example 2: {(k, x) for k in K for x in X if P(x)}
> >>
> >> This is another example in Python:
> >>
> >> s = {v for v

Re: list comprehension

2019-02-10 Thread Brad Gilbert
In

 {l for l in L}

The reason it is in `{}` is to create a Set from iterating over `L`.

> In Python, the set-builder's braces are replaced with square brackets, 
> parentheses, or curly braces, giving list, generator, and set objects, 
> respectively.

So in Python:

[ l for l in L ] gives a list
( l for l in L ) gives a generator
{ l for l in L } gives a set

In Perl6 those would most likely be written as:

L.List   or   L.Array   or   L.list
L.Seq
L.Set

---

The way to do that is

my \L = ((1..10) xx 3).flat.pick(*).list;

set( L ) # A
L.Set # B

my %set is SetHash;
{ ++%set{$_} for L }  # C

# D
do {
# add the {} syntax to create a Set (lexically)
my sub circumfix:«{ }» ( \L ) { L.Set };

{ $_ for L } # <--
}

Something that seems similar to me is `unique`

.say for L.unique;

By that I mean, some places where you would use a Set, it makes sense
to use `.unique` instead

---

As for `{(k, x) for k in K for x in X if P(x)}`

The easiest one to directly translate appears to be the Scala one

my \K = 1..10;
my \X = 5..15;

# for (k <- K; x <- X if P(x)) yield (k,x)
Set.new: gather {
for K -> \k {
for X -> \x {
if P(x) {
take (k,x);
}
}
}
}

Other ways:

Set.new: (K X[,] X).grep: -> ( \k, \x ) { P(x) }

Set.new: K X[,] X.grep: 

Set.new: K X[,] X.grep: 

Set.new: ( -> ( \k, \x ) { (k,x) if P(x) } for K X[,] X )

Set.new: ( -> \x { |(-> \k { (k,x) if P x } for K) } for X)

On Sun, Feb 10, 2019 at 10:26 AM mimosinnet  wrote:
>
> Hi all,
>
> I wonder what would be the Perl notation for 'set-builders', as exposed
> in this wikipedia article:
>
> https://en.wikipedia.org/wiki/Set-builder_notation#Parallels_in_programming_languages
>
> This is the Python notation:
>
> Example 1: {l for l in L}
> Example 2: {(k, x) for k in K for x in X if P(x)}
>
> This is another example in Python:
>
> s = {v for v in 'ABCDABCD' if v not in 'CB'}
>
> https://en.wikipedia.org/wiki/List_comprehension#Similar_constructs
>
> I have been playing with the code below. Nevertheless, I am unsure on
> how to use the code to define a set.
>
> Cheers!
>
> <--- Code
> #!/usr/bin/env perl6
>
> my @L = 1 .. 10;
> my @K = 1 .. 10;
> my @X = 5 .. 15;
>
> say "Example 1:";
> for @L -> $l {
>   print "$l " if $l ∈ @L;
> }
>
> say "\nExample 2:";
> for @K -> $k { for @X -> $x {
> print "($k, $x), " if ($k ∈ @K and $x ∈ @X and $x < 8);
> }}
> <---
>
> --
> (≧∇≦) Mimosinnet (Linux User: #463211)


Re: buf to integer?

2019-02-08 Thread Brad Gilbert
The next release of Rakudo with have read-int32.

To use it now you would need to build from the git repository, I think.

On Fri, Feb 8, 2019 at 7:56 PM yary  wrote:
>
> the perl6-native "read-int32" or native-but-experimental "unpack" are the 
> natural answers- they map well from problem to answer! There's a good example 
> of perl6's pack in this thread.
>
> read-int32 was mentioned without an example so...
>
> my Buf $x = Buf.new(0x00, 0xFF, 0x88, 0xAE,0x5D,0x5C,0x72);
>
> Buf:0x<00 FF 88 AE 5D 5C 72>
>
> > $x.read-int32(3,LittleEndian).base(0x10)
>
> ===SORRY!=== Error while compiling:
>
> Undeclared name:
>
> LittleEndian used at line 1
>
>
>  Oh darn, need Perl6.d for read-int32 and the Endian enums! Is 6.d packaged 
> for general use?
>
> -y
>>
>>


Re: valid values?

2019-03-03 Thread Brad Gilbert
The `where` clause is already a smart-match, adding `~~` to it is not
only redundant, it can cause confusing action at a distance.
(By that I mean the right side of `where` is exactly the same as the
right side of `~~`)

You wouldn't write this:

* ~~ (* ~~ 1|2|4|8|16)

So don't write this either:

… where * ~~ 1|2|4|8|16

---

It should be

sub mysub(Int $value where 1|2|4|8|16)
   {
  say "Got $value"
}

On Sun, Mar 3, 2019 at 4:16 AM Fernando Santagata
 wrote:
>
> Hi Todd,
> is this what you're looking for?
>
> sub mysub(Int $value where * ~~ 1|2|4|8|16)
> {
>   say "Got $value"
> }
>
> mysub 2; # Got 2
> mysub 3; # Constraint type check failed in binding to parameter '$value'; 
> expected anonymous constraint to be met but got Int (3)
>
> On Sun, Mar 3, 2019 at 11:09 AM ToddAndMargo via perl6-users 
>  wrote:
>>
>> Hi All,
>>
>> I want to pass an integer to a sub.  The only
>> valid values of the integer are 1, 2, 4, 8, and 16.
>>
>> Other than using "if" to test their values, is
>> there a way to state that an integer can only
>> have certain predefined values?
>>
>> Many thanks,
>> -T
>>
>> --
>> ~~~
>> Having been erased,
>> The document you're seeking
>> Must now be retyped.
>> ~~~
>
>
>
> --
> Fernando Santagata


Re: valid values?

2019-03-04 Thread Brad Gilbert
An Array isn't a type of Str.

@ ~~ Str; # False
Array ~~ Str; # False

You can have an array that has a type constraint.

(my Str @) ~~ Array[Str]; # True
(my @ of Str) ~~ Array[Str]; # True

Or you could check that all of the values of the Array are of some type.

(my @ = ) ~~ *.all ~~ Str
(my @ = ) ~~ (.all ~~ Str)

This is one of the few times that it is acceptable to have a ~~ in a
smart-match.

sub test1(:@array? where .all ~~ Str) { say 'ok' }

test1; # ok
test1 array => ; # ok

test1 array => (1,2,3);
# Constraint type check failed in binding to parameter '@array'; …

Somewhere on the Internet I layed out the rules that I think that
should normally be followed, but I am not sure where.

On Mon, Mar 4, 2019 at 5:32 AM Fernando Santagata
 wrote:
>
> Hi Brad,
>
> How far should I follow the rule that I should not use a smartmatch in a 
> where clause?
>
> I'm thinking of this:
>
> > sub test1(:@array? where Str) { say 'ok' }
> 
> > test1()
> Constraint type check failed in binding to parameter '@array'; expected 
> anonymous constraint to be met but got Array ($[])
>   in sub test1 at  line 1
>   in block  at  line 1
>
> > sub test2(:@array? where .all ~~ Str) { say 'ok' }
> 
> > test2()
> ok
>
> The where clause in test1() doesn't work, but is the clause in test2() 
> dangerous (action at a distance)? Should I rephrase it differently?
>
> On Mon, Mar 4, 2019 at 5:29 AM Brad Gilbert  wrote:
>>
>> The `where` clause is already a smart-match, adding `~~` to it is not
>> only redundant, it can cause confusing action at a distance.
>> (By that I mean the right side of `where` is exactly the same as the
>> right side of `~~`)
>>
>> You wouldn't write this:
>>
>> * ~~ (* ~~ 1|2|4|8|16)
>>
>> So don't write this either:
>>
>> … where * ~~ 1|2|4|8|16
>>
>> ---
>>
>> It should be
>>
>> sub mysub(Int $value where 1|2|4|8|16)
>>{
>>   say "Got $value"
>> }
>>
>> On Sun, Mar 3, 2019 at 4:16 AM Fernando Santagata
>>  wrote:
>> >
>> > Hi Todd,
>> > is this what you're looking for?
>> >
>> > sub mysub(Int $value where * ~~ 1|2|4|8|16)
>> > {
>> >   say "Got $value"
>> > }
>> >
>> > mysub 2; # Got 2
>> > mysub 3; # Constraint type check failed in binding to parameter '$value'; 
>> > expected anonymous constraint to be met but got Int (3)
>> >
>> > On Sun, Mar 3, 2019 at 11:09 AM ToddAndMargo via perl6-users 
>> >  wrote:
>> >>
>> >> Hi All,
>> >>
>> >> I want to pass an integer to a sub.  The only
>> >> valid values of the integer are 1, 2, 4, 8, and 16.
>> >>
>> >> Other than using "if" to test their values, is
>> >> there a way to state that an integer can only
>> >> have certain predefined values?
>> >>
>> >> Many thanks,
>> >> -T
>> >>
>> >> --
>> >> ~~~
>> >> Having been erased,
>> >> The document you're seeking
>> >> Must now be retyped.
>> >> ~~~
>> >
>> >
>> >
>> > --
>> > Fernando Santagata
>
>
>
> --
> Fernando Santagata


Re: hash copy

2019-03-24 Thread Brad Gilbert
You created a single Hash then assigned it to two variables.

Also `clone` always does a shallow clone.
So there will be two Hashes, but the values will still share the same
scalar container.
If you add a new key it won't be in the other Hash.

my $a = { a => 1 };
my $b = $a.clone;
$b = 2;

say $a; # {a => 1}
say $b; # {a => 1, b => 2}

$b = 3;
say $a; # {a => 3}

You could work around that by deleting the key first.

$b:delete;
$b = 5;

Or by creating the second Hash some other way

my $b = %( $a.pairs );
my $b = %( $a.kv );

my %b = $a;

Which shows that if you are dealing with a Hash it is probably better
to use a % variable.

If you want to define the type of Hash-like container you can:

my %b is Hash = $a;

my %b is BagHash = $a;
my %b is Bag = $a; # immutable

On Sun, Mar 24, 2019 at 6:11 AM Marcel Timmerman  wrote:
>
> Hi,
>
> I was wandering if the following is an assignment or a binding (or binding of 
> the entries);
>
> my Hash $sleep-wait = { :s1(4.3), :s2(2.1), :s3(5.3), :s4(10.4), :s5(8.7),};
>
> my Hash $sleep-left = $sleep-wait;
>
>
>
> I noticed that in the following piece of code the $sleep-wait hash entries 
> were set to 0
> I had to explicitly do a copy to let it function correctly; 'my Hash 
> $sleep-left = %(|$sleep-wait);'
> Also cloning didn't work.
>
> use v6;
>
> my Hash $sleep-wait = {
>
>   :s1(4.3), :s2(2.1), :s3(5.3), :s4(10.4), :s5(8.7),
>
> };
>
> my Hash $sleep-left = $sleep-wait;
>
> loop {
>
>   # get shortest sleep
>
>   my $t = 1_000_000.0;
>
>   my $s;
>
>   for $sleep-left.keys -> $k {
>
> if $sleep-left{$k} < $t {
>
>   $t = $sleep-left{$k};
>
>   $s = $k;
>
> }
>
>   }
>
>   # set back to original time
>
>   $sleep-left{$s} = $sleep-wait{$s};
>
>   note "Reset entry $s to $sleep-left{$s} (from $sleep-wait{$s})";
>
>   # adjust remaining entries
>
>   for $sleep-left.keys -> $k {
>
> next if $s eq $k;
>
> $sleep-left{$k} -= $t;
>
> $sleep-left{$k} = $sleep-wait{$k} if $sleep-left{$k} <= 0;
>
>   }
>
>   note "sleep for $t sec, entry $s";
>
>   sleep $t;
>
> }
>
>
> perl version;
>
> This is Rakudo version 2018.12-363-ga1c2e20d7 built on MoarVM version 
> 2018.12-117-gdcafbc4c7
> implementing Perl 6.d.
>
>
> Regards,
> Marcel