Need help getting perl array out of scalar context - arrays

I have a perl array I need to store in the following way:
$self->{spec}->{allImages} = #allImages;
Then I need to retrieve the contents later:
print Dumper($self->{spec}->{allImages});
This yields:
$VAR1 = 10;
(the number of items in the array).
How can I break out of scalar context and get $self->{spec}->{allImages} back as a list?

Each hash value can only be a scalar.
You must store a reference to the array:
$self->{spec}->{allImages} = \#allImages;
http://perldoc.perl.org/perlreftut.html will give you more tutorial.

You need to change the assignment:
$self->{spec}->{allImages} = \#allImages;
This creates an array-ref that you can use.

Related

2D Array Printing as Reference

I have the code similar to below:
my #array1 = (); #2d array to be used
my $string1 = "blank1";
my $string2 = "blank2";
my $string3 = "blank3";
my #temp = ($string1, $string2, $string3);
push (#array1, \#temp);
The reason I am assigning the strings and then putting them into an array is because they are in a loop and the values get updated in the loop (#array1 is not declared in the loop).
When I run my program, it only gives me a reference to an array rather than an actual 2D array. How can I get it to print out the content as a 2D array and not as a reference or flattened out to a 1D array?
I would like an output like [[blank1, blank2, blank3],....] so i can access it like $array1[i][j]
An array can only have scalars for elements. Thus this includes references, to arrays for example, what enables us to build complex data structures. See perldsc, Tom's Perl Data Structure Cookbook.
Elements of those ("second-level") arrays are accessed by dereferencing, so $array1[0]->[1] is the second element of the array whose reference is the first element of the top-level array (#array1). Or, for convenience, a simpler syntax is allowed as well: $array1[0][1].
If we want a list of all elements of a second-level array then dereference it with #, like:
my #l2 = #{ $array1[0] }; # or, using
my #l2 = $array1[0]->#*; # postfix dereferencing
Or, to get just a few elements of the array, but in one scoop -- a slice
my #l2_slice = #{$array1[0]}[1..2]; # or
my #l2_slice = $array1[0]->#[1..2]; # postfix reference slice
what returns the list with the second and third elements of the same second-level array.
The second lines are of a newer syntax called postfix dereferencing, stable as of v5.24. It avails us with the same logic for getting elements as when we drill for a single one, by working left-to-right all the way. So ->#* to get a list of all elements for an arrayref,->%* for a hashref (etc). See for instance a perl.com article and an Effective Perler article.
There is a thing to warn about when it comes to multidimensional structures built with references. There are two distinct ways to create them: by using references to existing, named, variables
my #a1 = 5 .. 7;
my %h1 = ( a => 1, b => 2 );
my #tla1 = (\#a1, \%h1);
or by using anonymous ones, where arrayrefs are constructed by [] and hashrefs by {}
my #tla2 = ( [ 5..7 ], { a => 1, b => 2 } );
The difference is important to keep in mind. In the first case, the references to variables that the array carries can be used to change those variables -- if we change elements of #tla1 then we really change the referred variables
$tla1[0][1] = 100; # now #a1 == 5, 100, 7
Also, changing variables with references in #tla1 is seen via the top-level array as well.
With anonymous arrays and hashes in #tla this isn't the case as elements (references) of #tla access independent data, which cannot be accessed (and changed) in any other way.
Both of these ways to build complex data structures have their uses.

Manipulating a 'dynamic' array in javascript

As part of my nightwatchjs testing script, I have a 'dynamic' array that I would like to add a character to.
So, at the moment my array has a value of 4000, but I would like this to read 4,000.
This means that I need to add a , to my array.
The issue I have however, is that this value could change the next time I run the test script, so it could be 10000 or 100000.
So I suppose what I'm asking is whether it's possible to "select a value 3 elements from the end of my array?"
So no matter what or how many elements are in the array, the array will read xx,000.
Any help would be much appreciated. Many thanks.
Does this array have a single value? If so, why is it an array instead of just a variable?
You can use toLocaleString() to add commas to a numeric value, but it will return a string and not a number.
let arr = [4000]
let num = arr[0]
let commas = num.toLocaleString()
console.log(commas)
// "4,000"

How to create an array of shapes in VPython?

I'm trying to create an array of spheres in VPython, each with a manually entered position. Something like:
ball[0] = sphere(pos=vector(-1,4,9))
ball[1] = sphere(pos=vector(-2,6,6))
ball[2] = sphere(pos=vector(0,6,1))
etc. The problem is that I keep getting an error reading "IndexError: list assignment index out of range". How can I resolve this issue?
see How to declare an array in Python?.
You also might want to consider using a compound
Modified code:
# https://stackoverflow.com/questions/56461496/how-to-create-an-array-of-shapes-in-vpython
from vpython import *
# https://stackoverflow.com/questions/1514553/how-to-declare-an-array-in-python
ball=[]
ball.append(sphere(pos=vector(-1,4,9)))
ball.append(sphere(pos=vector(-2,6,6)))
ball.append(sphere(pos=vector(0,6,1)))
Result:

Concise way to create an array filled within a range in Matlab

I need to create an array filled within a range in Matlab
e.g.
from=2
to=6
increment=1
result
[2,3,4,5,6]
e.g.
from=15
to=25
increment=2
result
[15,17,19,21,23,25]
Obviously I can create a loop to perform this action from scratch but I wondering if there is a coincise and efficent way to do this with built-in matlab commands since seems a very common operation
EDIT
If I use linspace the operation is weird since the spacing between the points is (x2-x1)/(n-1).
This can be handled simply by the : operator in the following notation
array = from:increment:to
Note that the increment defaults to 1 if written with only one colon seperator
array = from:to
Example
array1 = 2:6 %Produces [2,3,4,5,6]
array2 = 15:2:25 %Produces [15,17,19,21,23,25]

Initialize Array to Blank custom type OCAML

ive set up a custom data type
type vector = {a:float;b:float};
and i want to Initialize an array of type vector but containing nothing, just an empty array of length x.
the following
let vecarr = Array.create !max_seq_length {a=0.0;b=0.0}
makes the array init to {a=0;b=0} , and leaving that as blank gives me errors. Is what im trying to do even possible?
You can not have an uninitialized array in OCaml. But look at it this way: you will never have a hard-to-reproduce bug in your program caused by uninitialized values.
If the values you eventually want to place in your array are not available yet, maybe you are creating the array too early? Consider using Array.init to create it at the exact moment the necessary inputs are available, without having to create it earlier and leaving it temporarily uninitialized.
The function Array.init takes in argument a function that it uses to compute the initial value of each cell.
How can you have nothing? When you retrieve an element of the newly-initialized array, you must get something, right? What do you expect to get?
If you want to be able to express the ability of a value to be either invalid or some value of some type, then you could use the option type, whose values are either None, or Some value:
let vecarr : vector option array = Array.create !max_seq_length None
match vecarr.(42) with
None -> doSomething
| Some x -> doSomethingElse
You can initialize and 'a array by using an empty array, i.e., [||]. Executing:
let a = [||];;
evaluates to:
val a : 'a array = [||]
which you can then append to. It has length 0, so you can't set anything, but for academic purposes, this can be helpful.

Resources