77607

Assign a variable and check existence of hash key

Question:

With the little that I know about Perl, I was surprised that this syntax doesn't work:

if (exists $wid = $dict{$w}) { print "$wid:$c\n"; }

It seems I can't make the assignment $wid = $dict{$w} and check if it exists at the same time:

<blockquote>

exists argument is not a HASH or ARRAY element or a subroutine at createWordIndex.pl line 31.

</blockquote>

Is there a way to do this kind of assignment? Or do I just need to check existence first and then make the assignment if the condition is true?

Answer1:

Are you trying to figure out if there's a value there before you print it? Then you'll have to do it this way:

if ( exists($dict{$w}) ) { my $wid = $dict{$w}; print "$wid: $c\n"; }

If you know that the values stored will always be defined, you can do

if ( defined( my $wid = $dict{$w} ) ) { print "$wid: $c\n"; }

Answer2:

Alternatively (TIMTOWTDI, after all), you can use the smart match operator (for Perl version >= 5.10):

if($w ~~ (keys %dict)) { my $wid = $dict{$w}; print "$wid: $c\n"; }

Or, alternatively:

if(grep{$w eq $_}(keys %dict)) { my $wid = $dict{$w}; print "$wid: $c\n"; }

Answer3:

You just answered your question in your question.

<blockquote>

"Or do I just need to check existence first and then make the assignment if the condition is true?"

</blockquote>

the <strong>exists</strong> function in your code takes in the scalar $wid. And is clearly stated in your error that the exists function needs a hash or array element

<blockquote>

exists argument is not a HASH or ARRAY element or a subroutine at createWordIndex.pl line 31.

</blockquote>

so yes. you need to check first if it exists.

friendly advice: try all the things/solutions that you can think of before asking because you might already know the answer to your question. :)

Answer4:

you can do it, just skip the exists. if the assignment is made (because there is a $dict{$w}) the side-effect is true.

my %dict; $dict{one} = 1; $dict{two} = 2; $dict{three} = 3; if ($wid = $dict{four}) { print "$wid\n"; } else { print "NO!\n"; }

Recommend

  • Limiting file upload type
  • Can one compare java.lang.Class objects with == in Java? [duplicate]
  • grep for a string in a line if the previous line doesn't contain a specific string
  • Saving 30-Feb on Mysql (Date Formating)
  • Python Recursive Function for Collatz Conjecture
  • Check that all values in a range are identical
  • Formatting partial unknown dates with DateTime() from a database?
  • How to get the output from the comm command into 3 separate files?
  • Loop vectorization gives different answer
  • Use of eval to load modules
  • How can i compare more number of images in two folders using Perl
  • Undefined index errors accessing $_POST
  • Detect if user has closed ALL windows for a website?
  • Is it possible to manually check LocateRegistry existing?
  • How can I open a Windows CMD window for Perl and run a command?
  • Why VBA goes to error handling code when there is no error?
  • Is there anything wrong with using requires after output starts printing?
  • What's the point of nonfinal singleton objects in scala?
  • Javascript Array, Object, Date not defined
  • Losing my session variables
  • Ruby 1.8.6 Array#uniq not removing duplicate hashes
  • Get a trait object reference from a vector
  • Xmonad multiple submap key combos
  • php script is parsing content from RTE (tt_news) but internal links are not appearing as speaking ur
  • How can I mock ui-router's resolve values when testing a state's configuration?
  • NHibernate manually control fetching
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View
  • Why Encoding.ASCII != ASCIIEncoding.Default in C#?
  • one Local Olampyad Questions on Informatic in 2011
  • Yii2: Config params vs. const/define
  • Ajax Loaded meta Tags
  • Using $this when not in object context
  • Is there any way to access browser form field suggestions from JavaScript?
  • How do I fake an specific browser client when using Java's Net library?
  • How reduce the height of an mschart by breaking up the y-axis
  • Perl system calls when running as another user using sudo
  • Hazelcast - OperationTimeoutException
  • KeystoneJS: Relationships in Admin UI not updating
  • Net Present Value in Excel for Grouped Recurring CF