Main Menu

Perl query

Started by Alan Clifford, August 18, 2015, 02:05:48 PM

Previous topic - Next topic

Alan Clifford

I have a test that seems to be working differently in two different constructs.

$hour =~ /(.*):/

From the code fragment below, this is the difference:

hour: +0:30   hr:  +0
hour: -0:30   hr:  -0
hour: 0:30   hr:  0:30
hour: +0:30   hr:  +0
hour: -0:30   hr:  -0
hour: 0:30   hr:  0


#!/usr/bin/perl
#
use strict;
use warnings;

my $hour;
my @allhours ;
my $hr ;
push @allhours, "+0:30" ;
push @allhours, "-0:30" ;
push @allhours, "0:30" ;

foreach $hour ( @allhours ) {
  $hour =~ /(.*):/ and $hr = $1 or $hr = $hour ;
  print "hour: $hour\thr:  $hr\n" ;
}

foreach $hour ( @allhours ) {
  if ($hour =~ /(.*):/ ) {
    $hr = $1 ;
  }
  else {
    $hr = $hour ;
  }
  print "hour: $hour\thr:  $hr\n" ;
}


Phil Harvey

Hi Alan,

Tricky.

Your problem is that "0" is false in Perl (so $hr = $1 is false if $hr is "0").  Try this maybe:

  $hr = $hour =~ /(.*):/ ? $1 : $hour;

TIMTOWTDI :)

- Phil
...where DIR is the name of a directory/folder containing the images.  On Mac/Linux/PowerShell, use single quotes (') instead of double quotes (") around arguments containing a dollar sign ($).

Alan Clifford

As a Perl novice, I think I was trying to be too clever.