• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 314
  • Last Modified:

shift the % array with removal of the first element

I am doing the following

my(%array) = undef;

@array{@one) = @two;

After I assign like this I always have
the first element in %array (%array[0])
present but undefined.

I would like to shift it out.

Please help.

0
sstouk
Asked:
sstouk
  • 2
1 Solution
 
fragtasticCommented:
Hmmmmm

1. %array isn't an array, it's a hash;

2. If you want to undef something I'd use something like

undef @array;

It looks less like you are trying to assign something to @array.

3. Try changing your code to look like this. I'm not sure what it is you're trying to achieve, but this might be the way forward.

Are you trying to just create a variable at the start, or remove the value from one already in existence??

undef %hash;           # Use this to "erase" hash
my %hash;              # Or use this to create a local hash
$two = "Hello!!";
$hash{one) = $two;     # Now the key in %hash called one will have a value of whatever the scalar $two is. This was set earlier.

print $hash{one};      # This will print "Hello!!" to the screen. You are printing the value from %hash that has a key name of one;

So in smoother code.

my %colours;

$1 = "Blue";
$2 = "Red";

$colours{car} = $1;
$colours{truck} = $2;

print "My car is $colours{car}\n";
print "My truck is $colours{truck}\n";

Make sense? Or did you really want to use an array???


0
 
sstoukAuthor Commented:
Perfect Answer.
Thank You very much

the statement:
my %hash;

is all I needed.

Thaks again!
0
 
fragtasticCommented:
Looked at the title of your question.

If you want to work with an array. Do this.

@array = (one, two, three, four, five, six);
print "Array is @array\n";
$first = shift(@array);
print "After shifting, array is @array\n";
print "and the element shifted out is $first\n";

If you're trying to shift elements out of a hash, don't. The data in a hash isn't stored in order like an array. When you take a slice of an array, it always returns the same value. A hash wouldn't as you use the key to access the value, not the position in the array. For example, using the above code

$array[0]   would have a value of one (or two if you look at it afer the shift) and would always have that value

It seems like you need to be clear on the differences between arrays and hashes and know when to use each one.

Perhaps you could explain in more depth what you are trying to do and post some example code so I can help more.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now