[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] FW: why is $# used in this section of code?



Fun $#schedules = -1 conversation at $work[0].

 

Did you know that assigning to $#foo can truncate @foo? I didn't.

 

j

15 years later, still learning Perl.   :)

 

 


From: Sean Baker
Sent: Thursday, August 05, 2010 8:46 AM
To: Programmers
Subject: RE: why is $# used in this section of code?

 

I’ve never used $#schedules before but if you ever want to know the size of an array – 1 it beats doing a (scalar @schedules – 1) all the time.  Thanks for the tip Justin!

 

 

The specific example below is redundant.  “my @schedules” and “$#schedules = 1” do the same thing.  One is just “use strict” friendly.

 

main::(t.pl:4): my @schedules;

  DB<1> n

  DB<1> x @schedules

empty array

main::(t.pl:7): $#schedules = -1;

  DB<1> n

  DB<1> x @schedules

empty array

 

DB<4> push @schedules, 1

DB<5> push @schedules, 2

DB<6> push @schedules, 3

DB<7> x $#schedules

0  2

DB<8> x @schedules

0  1

1  2

2  3

DB<9> x scalar @schedules -1

0  2

 

 

From: Sean Baker
Sent: Thursday, August 05, 2010 8:15 AM
To: Programmers
Subject: why is $# used in this section of code?

 

Interesting.

 

Can anyone explain to me in English (well) what ‘ $#schedules = -1 ‘ is supposed to be doing in the code below?

 

 

 

      # Schedule can have multiple entries.  Let's insert them all.

      #

      my ($schedule) = $event->children('schedule');

      my @schedules;

      $#schedules = -1;

      my $count=0;

      foreach my $sched ( $event->children ) { 

         next unless ( $sched->tag eq 'schedule' );

         #my $tmpier_hash = {%$tmp_hash};

         my $tmpier_hash;

 

         my ($sd) = $sched->get_xpath('start_date');

         my ($ed) = $sched->get_xpath('end_date');

         $tmpier_hash->{'end_date'}   = $ed->text;

         $tmpier_hash->{'start_date'} = $sd->text;

 

         my ($booking_url) = $sched->get_xpath('booking_url');

         if ( $booking_url && $booking_url->text ) {

            $tmpier_hash->{'booking_url'} = $booking_url->text;

         } else {

            # No booking_url so we'll just use the venue url

            my ($vi) = $sched->get_xpath('venue_id');

            my $venue_id = $vi->text;

            $tmpier_hash->{'booking_url'} = $venues->{$venue_id};

         }

 

         push @schedules, $tmpier_hash;

      }