# Build a new Array from an array

Hello

I have an array. Its dynamic and i'll never know for definite how many elements there'll be in that array - all i know is that each element will be a set of characters separated by dashes. Here's one instance:

[ab-wl-uat1, bc-wl-uat1, pc-wl-uat1, bg-too-uat2]


I'm trying to recreate an array from that one inside a puppet manifest. All i want, though, is the set of characters after the last "-" from each element - so in this case i'd like to return:

[uat1, uat1, uat1, uat2]


I've tried so many things it's unreal! The nearest i get to something is this:

$old = [ab-wl-uat1, bc-wl-uat1, pc-wl-uat1, bg-too-uat2]$newarray = split(inline_template("<%= @old.join(',') %>"),'-')


But this just returns:

  [ab, wl, uat1,bc, wl, uat1,pc, wl, uat1,bg, too, uat2]


And i've tried to dynamically build a new array through iteration - it was something like this, which just didn't work at all:

$old.each |$x| {
$namein=inline_template("<%= @x.split('-')[-1] %>")$namearray=any2array($namein)$newarray = concat($namearray,$newarray)
notice($newarray) }  newarray just ended up being one element long (I suspect because variables are immutable in puppet?) Can anyone give me any pointers as to what i'm doing wrong, at all please? i'm on puppet 2016.1 Cheers! edit retag close merge delete ## 2 Answers Sort by » oldest newest most voted Actually, you do not need a custom function for this: $newarray = $old.map |$x| { split($x, '-')[-1] }  Note: I am still running puppet 3.X with future parser,$old.collect... works just fine here.

more

Thank you very much. worked like a charm.

( 2016-09-02 02:53:05 -0600 )edit

You can use custom function to build your new array, something like this.

[root@ha manifests]# cat ../lib/puppet/parser/functions/build_array.rb

module Puppet::Parser::Functions
newfunction(:build_array, :type => :rvalue) do |args|
new_array = []
args[0].each do |item|
item = item.split('-')[-1]
new_array.push(item)
end
new_array
end
end


You can use it like,

class usecase {
$newarray = build_array(['ab-wl-aut1', 'bc-wl-uat1', 'bg-too-uat2']) notify { "${newarray}": }
}


Output:

[root@ha manifests]# puppet apply ../tests/init.pp
Notice: Compiled catalog for ha.home in environment production in 0.75 seconds
Notice: [aut1, uat1, uat2]
Notice: /Stage[main]/Usecase/Notify[[aut1, uat1, uat2]]/message: defined 'message' as '[aut1, uat1, uat2]'
Notice: Finished catalog run in 0.56 seconds

more

Thanks you very much for taking the time / trouble to answer. I didn't use this answer but you've certainly given me an intro into building my own custom function.

( 2016-09-02 02:54:50 -0600 )edit