Albert Jones
Albert Jones

Reputation: 33

How to search/replace with random array value in perl from command line

I'm trying to search/replace where the replacement has a random value from an array -- all from the command line in Perl. I can't figure out what's wrong here. I've tried a lot of variations of this, and read many examples online (which are all for non-command-line).

 echo "Test z|Test z|Test z|" | tr '|' '\n' | \
 perl -pe '@numbers=[12.3, 45.6, 78.9]; $number = $numbers[rand @numbers];  s/z/" : ".( int ($number) )/ge'

The actual output is something like this (the numbers change):

Test  : 24591392
Test  : 24591752
Test  : 24591416

The expected output is:

Test  : 45.6
Test  : 12.3
Test  : 78.9

Where the actual numbers are randomly selected. Any tips are welcome, including pointing out silly typos. Thanks!

Upvotes: 1

Views: 91

Answers (1)

mob
mob

Reputation: 118595

You want to say @numbers=(12.3, 45.6, 78.9), not @numbers=[12.3, 45.6, 78.9]. The latter creates an array with a reference to another array as its only element. The output you are currently seeing is the numification of a reference value, not the contents of the array.

Upvotes: 3

Related Questions