Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: splitting the scalar variables in an array

by Athanasius (Chancellor)
on Nov 16, 2013 at 06:55 UTC ( #1062858=note: print w/replies, xml ) Need Help??

in reply to splitting the scalar variables in an array

split expects its second argument to be a string (i.e., a scalar), so using the array @TotalHosts here puts the array into scalar context, and split gets the number of elements in the array. You need to change this line:

my @dd = split "\n", @TotalHosts;

to something like this:

my @dd; push @dd, split "\n", $_ for @TotalHosts;

which calls split on each element of the array in turn. This works provided that each of the array elements is a string.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: splitting the scalar variables in an array
by afoken (Abbot) on Nov 16, 2013 at 09:13 UTC
    my @dd; push @dd, split "\n", $_ for @TotalHosts;

    No need for push and for:

    my @dd=map { split "\n" } @TotalHosts;


    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re^2: splitting the scalar variables in an array
by sunil9009 (Acolyte) on Nov 17, 2013 at 10:44 UTC

    Thanks for the help, I modified the code but that didnt helped either. The scalar value for @dd returned by the code is as follows 1 1 4 Thats because Hostclass-A has 1 host, Hostclass B has 1 and C has 4 hosts. I want scalar(@dd) to be just 6 ( each host should be a separate element in an array )

    sub gethosts { foreach $class(@hostclass) { chomp (@hosts_per_hostclass = `/opt/systems/bin/expand-hostclass --hos +ts -r $class`) ; my @dd; push @dd, split "\n", $_ for @hosts_per_hostclass; print scalar(@dd) , "\n"; } }

      Consider this resolved, foreach was printing it 3 times. Final working code is as follows. Thanks to all of you guys fo the pointers.

      sub gethosts { foreach $class(@hostclass) { chomp (@hosts_per_hostclass = `/opt/systems/bin/expand-hostclass --hos +ts -r $class`) ; #print "@hosts_per_hostclass \n"; push @dd, split "\n", $_ for @hosts_per_hostclass; } return @dd; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062858]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2018-02-20 02:10 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (266 votes). Check out past polls.