Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Don Coyote's scratchpad

by Don Coyote (Pilgrim)
on Jul 01, 2010 at 17:29 UTC ( #847567=scratchpad: print w/replies, xml ) Need Help??

*work in Progress*

Unlike Perl6, objects in Perl5 are a matter of terminology, rather than an implicit construct of the language.citation needed

~ Belief in Objects is a practised meditation here at the monastery.

At this stage you have a general understanding of programmatic concepts of perl. Including, but not limited to:add links to examples of concepts

  • Variables
  • Data types
  • Subroutines - especially argument passing
  • Symbols - especially names and references
  • Program Flow
  • and a sprinkle of importing

A subroutine takes a list as an argument. This translates into flattened interpolation of array variables. The remedy to which is to pass array variables in by reference.

# example of pass by reference

Another way to do this instead of passing the ref as an argument, is to call the subroutine on the ref. As code tricks go, this can get fairly dangerous fairly quickly. So as an intention any ref you would like to be able to have this ability will need to be anointed.

To anoint a variable reference it is blessed.anoint vs bless meanings look up required

# bless $var;

Now we have another way to call the subroutine. We start by dereferencing the reference, but instead of making an element access, we replace the index identifier with the subroutine to be called.

$arrvar->[0]; # deref array element access $arrvar->{'anoint'}; # deref hash element access $arrvar->subroutine; # deref subroutine call

TODO: separate out the element access and subroutine call, and explain why

not actually dereferencing, just uses the same symbol in a similar way, to act in a different way. A Symbolic Synonymcitation needed of sorts

$arrvar->subroutine; # deref subroutine call

theres a couple of notes to make here. the dereference is not accessing an element, and considering you are calling a subroutine on an array, you might expect that the array is magically passed into the argument list. well. it is not. hmmph

However, what is passed in, as the first argument, is the reference. Instant Data! Yippee! All you need do now is treat the ref as you would any normal ref argument.

The responsibility now lays in the subroutine. The subroutine will need to be house-trained. If you start feeding it all sorts of garbage, your carpets will look all sorts of messy. That is, the subroutine should be expecting the data it is receiving - of which it is the recipient.

sub iexpectanarraycontainingdataaboutaccuracy{ my $arrayref = shift; ## todo: not ideal example ## also align 0/9 with degugging levels print {STDOUT} $arrayref->[0]," is quite accurate\n" print {STDOUT} $arrayref->[9]," is deeply inaccurate\n" return 1; }

wheres the second note?

should you pass an hash reference by error, firstly, you did not bless an hash reference yet so that is unlikely, secondly, messy carpets.

This is a good time to think about writing a separate script to run tests against your script. Necessary ?

ah here it is!

Is that inheritance tax seems decidedly simple

Another consequence of invoking a subroutine on a blessed reference, is that the reference can only call subroutines that exist within the same package. At least in this case, as only the reference has been blessed in the one-argument form of bless. Suffice to say, this prevents the problem of that newly blessed reference being able to call random subroutines from other loaded packages.

But to stress again, it may call any routines in the same namespace, so you should also be aware to write the other subroutines to fail correctly should they be called erroneously

#!perl use 5.10.1; use strict; use warnings; use Carp; my @array_var = qw/Double, double toil and trouble;/; say join "\n","\nfirst:", @array_var; add_an_item( \ @array_var, $_ ) foreach qw/1234 abyzABYZ 4the5scottish6play 1when 2shall 3we 4three +!/; say join "\n","\nsecond: ",@array_var; my $array_ref = \ @array_var; bless $array_ref; $array_ref->add_an_item( $_ ) foreach qw/1234 Fire burn, and cauldron bubble./; say join "\n","\nthird: ", @array_var, "\nfourth: ", @$array_ref; sub add_an_item{ say "\nsub args: ", join ' ', @_; my $avref = shift; my $item_to_add = shift; # <STDIN> # use input module or this $item_to_add =~ tr/a-zA-Z//cd; $item_to_add || carp( "Skipping item.\nItems added to this array shou +ld contain letters." ) && return; $avref->[ @$avref ] = $item_to_add; } exit (0);

a note on inheritance

so in theory...

unless(eval{ $arrayref->can(maxstr) }){ carp $@ }else{ $arrayref->maxstr() } # carps


#!perl use 5.10.1; use strict; use warnings; use Carp; use parent qw'List::Util'; ... unless( $arrayref->can('maxstr') ){ carp $@ }else{ $arrayref->maxstr() } exit; #(?) :D

Hello wa5nti and welcome to the monastery.

Where to start? There could be many reasons for this occurence, so I can only make suggestions.

I was struck by the fact that your installation was attempting to install the perldoc program. In my experience Strawberry auto installs this. I find the documentation an inextricable part of the language and its distributions.

Non-installation of perldoc in Strawberry occurs when a certain config variable is defined at install time.

=item C<versiononly>

From F<versiononly.U>:

If set, this symbol indicates that only the version-specific
components of a perl installation should be installed.
This may be useful for making a test installation of a new
version without disturbing the existing installation.
Setting versiononly is equivalent to setting installperl's -v option.

In particular, the non-versioned scripts and programs such as
a2p, c2ph, h2xs, pod2*, and perldoc are not installed
(see C<INSTALL> for a more complete list). Nor are the man
pages installed.
Usually, this is undef.

Heres a one liner to see if this variable was defined at installation.

windos% perl -Mv5.20 -Mstrict -MConfig -w -e "say $Config{versiononly} +"

Should you find this variable is defined in some way, the simplest method would most likely be to re-install taking care not to install a version dependant version.

Other than that there are a huge number of variables, that do not show up in the perl -V invocation. Given the difficulty of being able to run perldoc, you may find a look at some of the path variables in the list lead you somewhere useful.

#!perl use 5.20; use strict; use warnings; use Config qw/config_sh/; open my $fh, '>', '.\configlist.txt' or die $!; print {$fh} config_sh(); close $fh;

This will provide a list something along the form of what can be seen here Example Config Variable Listing (note: Example is defined as relating to use in this forum reply, not the code itself).

Maybe check libpath variables in this list, and also permissions on the directories the paths indicate. For TMP paths, I usually see a shortname as upper case suffixed with tilde V:\STRAWB~\lib\path\

Pod is included with modules, you can check the scripts directly, and Pod is accessible through online sources CPAN Perl5

Perl is Perl, if none of this helps, maybe consider re-installing Active-State, as it was working for you previously, until you are more familiar with the language.

I hope this helps. Local access to all the really useful beginners documentation is essential for a good learning experience.

Why are you re-inventing the wheel? So I can test it goes round!

post 3 How do I write a program that calculates the sum of all numbers to a number, n? silly response given

This response is not intended to be taken literally. :p

The sum of ALL numbers being 1/12, would the sum of all numbers up to N not be some type of a function? In the manner of

sum( N,N-1,N-2..N=1 ) = N / ( 1/12 )

Oh yes, I see now n(n+1)/2, overthinking it again.

Although that might be N * 1/12 (but is probably neither). For another undefined definition, maybe just bitmasking the sum of all numbers to length N. This could work well if soan is truly irrational.

sub donotrun_this_is_an_example{ use constant Soan = (1/12); my $bitmask = ~ -256**($n/8); return Soan & $bitmask; }

similar idea would be to return the of multiplying Soan by 10 to power of N: int( Soan*10**$n )

Alert! vague conjecture recollection syndrome and Random thought process combination.

post 2

To replace the occurence string in perl

Off the top of my head (untested), I would suggest starting with a one liner such as:

perl -pi.bak -e " use features qw/state/; state $nameshash = { 'Poole' => 1 }; s/(<.*?CIT-)(\w+)(-\w\d+.*?>)/"$1$2".$nameshash->{$2}++."$3"/ge; " bibliofile

post 1

CRC-16 algorithm


print "CRC16 in hex:\n  ", unpack('H*', pack('S', $crc16)), "\n";

citation needed check pack pod.
This could be a problem caused by the use of unpack() on pack() - recalling some usage where internal representation does not necessarily behave to standards of other specifications.

post 0

  • iteration vs recursion: the iterator should do what its told. that is it should have an expected behaviour as of any particular version, though that behaviour can change. It is for the programmer to be up to date with the current usage.
  • Behaviour: can change as with anything, take for example hash behaviour, modified in regards of security (re collisions). The random nature of the iteration, should not be used as a defined behaviour, yet knowledge of that behaviour allows quick development. (uhm iteration or storage/retrieval different things?).
  • User configurable: perhaps user accessible. same thing maybe. For example, I can access symbol tables, which behave in a defined way. In general I do not need to access the stashes, but I can if I want to. A cost effective implementation, (will out perform in drag races), which can be user interactive/manipulated. (we want it to turn doughnuts). Basically, I don't want to be setting loads of flags. If I need to define the behaviour outside of the general dwimness of the iterator, I can set about writing some routines to do so. This also encourages legacy code to have documented implementations.
  • user defined operator: something along this line maybe.
  • DWIM: when I want it to invalidate on a resize operation, it should. When I don't want it to invalidate on a resize operation it should not. In my dreams, I want it do both within one.
  • TMTOWTDI: There would not be any need to write code if the compiler already knew what I wanted to do.
  • seem to be straying away from iterator behaviour a bit now...
  • Common complex usage requirement:
my %combinations = ( co1 => [ [ qw(one two three four five) ], [ qw(one one two three five) ] ], co2 => [ [ qw(one two three five seven) ], [ qw(one one two three five) ] ], co3 => [ [ qw(one two three five seven) ], [ qw(one two three four five) ] ], co4 => [ [ qw(one two three five seven) ], [ qw(one two three four five) ], [ qw(one one two three five) ] ], ); reorg($_,\%combinations) foreach(keys %combinations); sub reorg{ my($k,$h) = @_; foreach my $combiset(@{$h->{$k}}){ my @uniquesets = grep $_ =~ /\Aus/ keys %combinations; my $num = scalar(@us); foreach my $set ( @$combiset ){ $combinations{'us'.++$num } = $set unless grep @$set {<~~>} @$_, @combinations{@us}; # where {<~~>} is 'these arrays match' # or the front N indices do or ... } }

To end up with something like:

%combinations = ( co1 => [ [ qw(one two three four five) ], [ qw(one one two three five) ] ], co2 => [ [ qw(one two three five seven) ], [ qw(one one two three five) ] ], co3 => [ [ qw(one two three five seven) ], [ qw(one two three four five) ] ], co4 => [ [ qw(one two three five seven) ], [ qw(one two three four five) ], [ qw(one one two three five) ] ], us1 => [ qw(one two three four five) ], us2 => [ qw(one two three five seven) ], us3 => [ qw(one one two three five) ], );

While writing this example, I felt as though most of writing code is iterator definition. Within this example, I require several uses of iterator to define growing numbers of keys, these themselves need to be used to clarify the keys the initial map operation continues to apply the reorganising routine on the hash to. While also not then applying the new keys which have been added.

A kind of There's More Than One Way To Do What I Mean? I mean the iterator to know the keys I started with, and only iterate through them as the hash grows. I mean another iterator to build a set of unique values keyed in the original hash, and built out of the original keys values. I mean the newly built unique values to be used straight away in validation checks on the remaining keys.

If as here, I approach designing the code without considering what the internal behaviour of the iterator is, other than the existing definition that it should not be relied upon. The internal iteration behaviour may change between versions, and the code is easily maintained throughout minor transitions.

What I need from the iterator is that, a defined behaviour. If it is not of any impact as to the precise implementation, as the code is not well designed if it relies on that, then would it not be reasonable to approach implementation as a matter of cost and efficiency. What is the fastest, most cost effective implementation? Can that implementation be reasonably identified as being compatible for the next 15+ years. Can I access it and incant wizardry in the way I might with symbol tables. Such as by having a user defined operator.

Perhaps something more robust, like a Global Iterator Variable / Symbol, along the lines of ${*} or *INC,*ARGV, the match array $-[0..-1]. I don't want to be setting variables and flags in most cases. I want to have a simple concept of, don't rely on this behaviour, but this is how you can manipulate it if you want to. And consider maintainer is a must, will the code self-document?

Log In?

What's my password?
Create A New User
[Corion]: Ah - if that information is saved in a file, then you could theoretically spam that file and confuse getlogin(). So, don't use it for authentication :)
[tye]: that is what getlogin() certainly *used* to do. I don't believe that is what it certainly should do.
[davido]: /var/run/utmp is 664 i think.
[tye]: Note that my "man getlogin" says that it uses stdin when it should use /dev/tty (calling a glibc bug). But that does not appear to be the case when I test it. But maybe Perl's getlogin() is not using glibc's getlogin().
[oiskuu]: well, run a strace and see what the getlogin does for you.... As I said. SELinux probably has those security labels. But not regular linux.
[tye]: for example, read https://unix. questions/146138/ loginuid-should-be -allowed-to-change -or-not-mutable-or -not
[tye]: I'm not using SELinux and it certainly appears to disagree with you. shrug
[tye]: Since you brought up /proc, oiskuu, I didn't see you respond to my suggestion of 'loginuid'. Does your /proc not have such?

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2017-06-23 19:46 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (554 votes). Check out past polls.