"Sputnik" help  
Sputnik Help
Language Reference - Datatypes - Arrays (List)

Arrays (List)

In Sputnik, an array can also function as a list, providing a way to store and access elements in a sequential manner.

A list array is created using the array() function or the [] syntax, where elements are defined with consecutive integer indices starting from 0. This allows for easy indexing and retrieval of elements based on their positions within the list.

In order to be a list that passes the IsList check it must not contain any string keys and the numeric keys must travel from 0 to count-1 of the array. However an array does not need to pass the IsList check to be a useful array! You can use arrays however you want.

Here's an example of creating and using a list array:

my $list = ["Apple", "Banana", "Orange"];
printr $list;

// PRINTS
// Array
// (
//     [0] => Apple
//     [1] => Banana
//     [2] => Orange
// )

In the above example, we create a list array $list with three elements: "Apple", "Banana", and "Orange". Each element is assigned a numeric index starting from 0.

List arrays can be accessed and manipulated using their indices. For example, to retrieve an element from a specific position in the list, you can use the corresponding index:

my $list = ["Apple", "Banana", "Orange"];
say $list[1]; // Output: Banana

You can also modify elements in a list array by assigning new values to their respective indices:

my $list = ["Apple", "Banana", "Orange"];
$list[2] = "Grapes";
printr $list;

// PRINTS
// Array
// (
//     [0] => Apple
//     [1] => Banana
//     [2] => Grapes
// )

In the above code, we update the element at index 2 to be "Grapes", resulting in the modified list array.

List arrays are useful when dealing with sequential data, such as a collection of items where the order matters. They provide efficient access and manipulation of elements based on their numeric positions within the list.

Here are two examples showcasing how to iterate over list arrays using a for loop and a foreach loop:

Using a for loop:

my $list = ["Apple", "Banana", "Orange"];
for (my $i = 0; $i < length($list); $i++)
{
    say "Element at index $i: " . $list[$i];
}

// PRINTS
// Element at index 0: Apple
// Element at index 1: Banana
// Element at index 2: Orange

Using a foreach loop:

my $list = ["Apple", "Banana", "Orange"];
foreach (my $element in $list)
{
    say "Element: " . $element;
}

// PRINTS
// Element: Apple
// Element: Banana
// Element: Orange

Please note that list arrays and associative arrays share the same underlying data structure in Sputnik. The distinction between them lies in the keys used for accessing elements: list arrays use integer indices, while associative arrays use string keys.

For more advanced operations and functionalities related to arrays, please refer to the main Arrays section and Associative arrays section.


Contact
Cheryl (uberfox@hotmail.com)
Homepage
http://ubersoft.org