简体   繁体   中英

shift an array from the values passed to subroutine in Perl

I am passing some undefined no. of arrays to the subroutine in perl I want to get these individual arrays in the subroutine and so I can run loop. But as i was unable so I tried passing the count of arrays. But as we can remove individual elements from an array using shift can we do same with array ie is there some function similar to Shift for array.

sub iFrame
{
    my $count=shift @_;

    for (my $i=1;$i<=$count;$i++)
        {
         my @iFrame =@_; #need to remove this @iFrame each time
         print qq[<iframe src="$iFrame[0]" width="$iFrame[1]" 
         height="$iFrame[2]" frameborder="$iFrame[3]" name="$iFrame[4]"></iframe>];
             # and some other code
        }

A better solution would be if I am able to do the same without passing the $count of arrays.

Best way is to pass a reference to the array, then dereference it in the subroutine. Like this:

use strict;
my @array = qw(a b c);
mysub(\@array);

sub mysub
{
  my @array = @{$_[0]};
  foreach (@array)
  {
    print $_
  }
}

Pass them as references.

sub iFrame
{

    for my $iFrame (@_)
        {
         print qq[<iframe src="$iFrame->[0]" width="$iFrame->[1]" 
         height="$iFrame->[2]" frameborder="$iFrame->[3]" name="$iFrame->[4]"></iframe>];
             # and some other code
        }
}

iFrame(
   [ $src1, $width1, $height1, $frameborder1, $name1 ],
   [ $src2, $width2, $height2, $frameborder2, $name2 ],
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM